如何在 JTextArea 上写下所有单词,即使每一行有多个单词?

问题描述 投票:0回答:1

我正在制作一个词法分析器,我似乎无法找到通过 JTextArea 并取出上面写的所有单词的方法,以便我可以将它们与正则表达式进行比较并继续分析器。我显然在 Java 工作。

我试图获取文本,但它把所有在同一行上的单词都抛给了我。

java swing user-interface compiler-construction lexical-analysis
1个回答
0
投票

你是这个意思吗?下面的代码获取 JTextArea 中的文本,删除所有带有空格的标点符号和数字,然后根据一个或多个空格拆分文本。阅读代码中的注释:

String[] words;
String text = jTextArea1.getText();
if (!text.isEmpty()) {
   // Remove all puctuations and digits
   text = text.replaceAll("\\p{Punct}|\\d+", " ");
   /*Split `text` into the `words` array based 
     on one or more whitespaces:           */
   words = text.split("\\s+");
}
else {
    System.out.println("No Text To Process!");
    return;
}
    
//Sort the `words` array:
Arrays.sort(words);
    
/* List the words contained within the `words` array
   in columnar format (6 columns):    */
System.out.println("Words in JTextArea:");
System.out.println("===================");
  
int cnt = 0;
for (String str : words) {
    if (cnt == 6) {
        System.out.println();
        cnt = 0;
    }
    System.out.print(String.format("%-20s", str));
    cnt++;
}
System.out.println();
© www.soinside.com 2019 - 2024. All rights reserved.