[英]Java regex issue (negative lookahead & lookbehind)
I need your help guys,.我需要你们的帮助,伙计们。 This is a tricky java regex issue.
这是一个棘手的 java 正则表达式问题。 been search for a solution for a couple hours.:.
几个小时以来一直在寻找解决方案。:. Here it is:
这里是:
In the following text, I want to match the "boat" word...在下面的文字中,我想匹配“船”字......
I have a boat to sell.
我有一条船要卖。 It comes with extra boat propellers but does not come with a boat trailer (the boat is pretty big so you might need a boat propeller trailer too).
它带有额外的船用螺旋桨,但没有船用拖车(船很大,所以您可能也需要船用螺旋桨拖车)。 I used to have a bunch of boats but my passion for a boat faded with time.
我曾经有很多船,但我对船的热情随着时间的推移而消退。 I did not think people would have interest for a bunch of boats but this is my last one, so Yeéé: :)
我不认为人们会对一堆船感兴趣,但这是我的最后一艘,所以 Yeéé::)
I got this example setup in regex 101 ( https://regex101.com/r/o6S4SP/22 ) but it's not working properly:-(我在正则表达式 101 ( https://regex101.com/r/o6S4SP/22 ) 中得到了这个示例设置,但它不能正常工作:-(
PS: I'm using Regex101 for the example but "(SKIP)(FAIL)" is not supported in Java's regex syntax. PS:我使用 Regex101 作为示例,但 Java 的正则表达式语法不支持“(SKIP)(FAIL)”。
Hope anyone could help:-)希望任何人都可以提供帮助:-)
You may use the following regex in Java that features a constrained-width lookbehind pattern (supporting limiting quantifiers):您可以在 Java 中使用以下正则表达式,该正则表达式具有受限宽度的后向模式(支持限制量词):
(?<!\bfor\sa\s(?:bunch\sof\s){0,1})(?:\bbunch\s+of\s+)?\bboats?\b(?:\s+propellers?)?+(?!\s+trailers?\b)
See the Java regex demo online (proof) . 在线查看 Java 正则表达式演示(证明) 。
In Java,在 Java 中,
s = s.replaceAll("(?<!\\bfor\\sa\\s(?:bunch\\sof\\s){0,1})(?:\\bbunch\\s+of\\s+)?\\bboats?\\b(?:\\s+propellers?)?+(?!\\s+trailers?\\b)", "<b>$0</b>");
Regex details正则表达式详细信息
(?<?\bfor\sa\s(:,bunch\sof\s){0,1})
- a negative lookbehind that fails the match if, immediately to the left of the current location, there is (?<?\bfor\sa\s(:,bunch\sof\s){0,1})
- 如果在当前位置的左侧紧邻有
\bfor\sa\s
- for
, whitespace, a
, whitespace \bfor\sa\s
- for
, 空格, a
, 空格(?:bunch\sof\s){0,1}
- 0 or 1 occurrences (ie an optional occurrence) of bunch
, whitespace, of
, whitespace bunch
(?:bunch\sof\s){0,1}
- 0 或 1 次出现(即可选出现) bundle , whitespace, of
, whitespace(?:\bbunch\s+of\s+)?
- an optional occurrence of bunch
, 1+ whitespaces, of
, 1+ whitespaces bunch
,1+ 个空格, of
,1+ 个空格\bboats?\b
- a whole word boat
or boats
\bboats?\b
- 一个完整的单词boat
或boats
(?:\s+propellers?)?+
- an optional occurrence of 1+ whitespaces followed with propeller
or propellers
. (?:\s+propellers?)?+
- 可选出现 1+ 个空格,后跟propeller
或propellers
。 NOTE : the ?+
possessive quantifier is key here to make the next lookahead only execute after this group pattern.?+
所有格量词是这里的关键,以使下一个前瞻仅在此组模式之后执行。(??\s+trailers?\b)
- a negative lookahead that fails the match if, immediately to the right of the current location, there is 1+ whitespaces, and then trailer
or trailers
as a whole word. (??\s+trailers?\b)
- 如果紧邻当前位置的右侧有 1+ 个空格,然后是一个或多个trailer
trailers
作为一个完整的单词,则匹配失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.