问题
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