Search code examples
regexmatchpartial

regular expression dont allow partial matching


Okay, first off I have strained relationship with regex. I can usually manage to make it grab or validate the data I need. But now it really feels like I've hit the regex wall.

I have concatinated strings of userdata that I need to validate.
They look something like: john|45|some|data|00111{more|data
The {more|data-part should be able to happen 0 or more times, but if I just use (regex)*. Then if one part fails, the string is still partially matched. I want it to fail the match in this case.

To simplify my case: I want foo, foobar, foobarbar to validate. But foobarcar and foobat to fail the validation.

foo(?:bar)* Will match all (last 2 only partially)

...if at all possible I would like to keep the "dont capture" part (?:).

From what I can tell, the solution might be in LookAround, a DontAllowPartialMatches parameter in the code, or splitting the string and validating the parts individually...

Any help is greatly appreciated.


Solution

  • Explicitly match the end of a string (or possibly line, depending on your dialect) using $:

    foo(?:bar)*$
    

    This will match foo, foobar, foobarbar, etc., but not foobarcar or foobat, as you wanted.

    (It will also match barfoobar, though, so if that's a problem, you'll probably want to use ^ to match the start explicitly too. ^foo(?:bar)*$)