突出显示正则表达式java

时间:2015-04-22 17:06:42

标签: java regex

我想使用Java突出显示文本中的匹配单词。我提出了申请,但由于某种原因,下面的代码无效。有人能告诉我发生了什么事吗?感谢。

integerForKey:

`

1 个答案:

答案 0 :(得分:0)

您正在跳过找到的文字。

while (matcher.find())
{
    txtarea2.setText( txtarea1.getText());
}

让我们说文本中间有一个匹配项。第一次find为真时,您将在txtarea2上设置文字。现在我们转到循环的顶部,再次调用find。现在,startend的位置会传递找到的文字,因此您无法从

获取正确的索引
int p0 = matcher.start();
int p1 = matcher.end();

事实上,我测试了这个流程并且实际上得到了一个例外。这是测试代码:

    Pattern pattern = Pattern.compile("a");
    Matcher matcher = pattern.matcher("bbbbbbbabbbbbb");

    while(matcher.find()){
        System.out.println("Found!");
    }

    System.out.println("start = " + matcher.start());
    System.out.println("end = " + matcher.end());

此处输出(第23行是对matcher.end()的调用)

Found!
Exception in thread "main" java.lang.IllegalStateException: No match available
    at java.util.regex.Matcher.start(Matcher.java:343)
    at com.conan.faker.Bar.main(Bar.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

Process finished with exit code 1