regex - highlight the regular expression java -
i want highlight matching words in text using java. made application, reason code below not working. can tell me what's going on? thanks.
pattern = pattern.compile(txt1.gettext()); matcher = pattern.matcher( ""+txtarea1.gettext()); while (matcher.find()) { txtarea2.settext( txtarea1.gettext()); } matcher.group(); highlighter h = txtarea2.gethighlighter(); highlightpainter painter = new defaulthighlighter.defaulthighlightpainter(color.yellow); int p0 = matcher.start(); int p1 = matcher.end(); try { h.addhighlight(p0, p1, painter); } catch (badlocationexception ex) { logger.getlogger(re.class.getname()).log(level.severe, null, ex); }
`
you're skipping on found text.
while (matcher.find()) { txtarea2.settext( txtarea1.gettext()); }
let's there match in middle of text. first time find
true you'll set text on txtarea2
. go top of loop , find
called again. positions of start
, end
passed found text won't correct indexes
int p0 = matcher.start(); int p1 = matcher.end();
in fact, tested flow , exception. here's test code:
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());
here's output (line 23 call matcher.end()
)
found! exception in thread "main" java.lang.illegalstateexception: no match available @ java.util.regex.matcher.start(matcher.java:343) @ com.conan.faker.bar.main(bar.java:23) @ sun.reflect.nativemethodaccessorimpl.invoke0(native method) @ sun.reflect.nativemethodaccessorimpl.invoke(nativemethodaccessorimpl.java:62) @ sun.reflect.delegatingmethodaccessorimpl.invoke(delegatingmethodaccessorimpl.java:43) @ java.lang.reflect.method.invoke(method.java:483) @ com.intellij.rt.execution.application.appmain.main(appmain.java:140) process finished exit code 1
Comments
Post a Comment