Regex Lookahead and Lookbehinds: followed by this or that

青春壹個敷衍的年華 提交于 2019-12-01 13:31:28

As you tagged your question yourself, you need lookarounds:

String regex = "(?<=\\W|^)(" + Pattern.quote(words.toString()) + ")(?= |[(])"
  • (?<=X) means "preceded by X"
  • (?<!=X) means "not preceded by X"
  • (?=X) means "followed by X"
  • (?!=X) means "not followed by X"

What about the word itself: will it always start with a word character (i.e., one that matches \w)? If so, you can use a word boundary for the leading condition.

"\\b" + theWord + "(?=[\\s(])"

Otherwise, you can use a negative lookbehind:

"(?<!\\w)" + theWord + "(?=[\\s(])"

I'm assuming the word is either quoted like so:

String theWord = Pattern.quote(words.toString());

...or doesn't need to be.

If you don't want a group to be captured by the matching, you can use the special construct (?:X)

So, in your case:

"(?:\\W?)(" + words.toString() + ")(?:\\s | \\()"

You will only have two groups then, group(0) for the whole string and group(1) for the word you are looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!