Regex match pattern after positive look ahead

时间秒杀一切 提交于 2019-12-11 10:05:23

问题


I have a regex that is doing a positive lookahead. The positive lookahead relies on "cfu/ml" being present in the string but doesn not include it in the result.

Here's the regex:

((((less|greater)\s*tha[nt]\s*)?[><]*[\d]+[\sx,.-]*)*)+(?=CFU\s?/\s?ML)

Ex string: "100,000,000 x 85 x 9345 cfu/ml"

Match1: "100,000,000 x 85 x 9345"

That's working just fine, but trying to match anything after that positive lookahead is not working. What I'm trying to do is add another result capture group after the positive look ahead like so.

((((less|greater)\s*tha[nt]\s*)?[><]*[\d]+[\sx,.-]*)*)+(?=CFU\s?/\s?ML)\s*blah

Ex string: "100,000,000 x 85 x 9345 cfu/ml blah"

Match1: "100,000,000 x 85 x 9345"

Match2: "blah"

Seems like nothing after the positive look ahead works, anyone know how I can fix this?


回答1:


Lookaheads are zero-width -- they don't match any characters, they just assert that certain conditions are true at that point in the string. So if the lookahead matches, then the characters after it will be CFU / ML or whatever else your lookahead would match.

You want to ignore those characters, though -- which means not just asserting they exist, but actually consuming them so they don't become part of a match group. For example, you might make your lookahead be a non-capturing group instead. The full matched string will still have those extra chars in it, but the capture groups won't include them.



来源:https://stackoverflow.com/questions/26935128/regex-match-pattern-after-positive-look-ahead

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