I’m trying to take a string that looks something like
"[go]$$Bcm11 Prisoners:"
and match the Bcm11 portion. Every single portion of it is optional (except technically, if the m appears, the , so I’m using the regex:
/([bBWw])?(c?)m?([0-9]*)/
Unfortunately, this cheerfully matches the empty string. Removing a ‘?’ or ‘*’ gets the right behavior, but makes that component non-optional.
Is there any way to force this regex to match a non-empty string when it’s available?
Use a lookahead
(?=...)to make sure there’s something in the string.This makes sure that at least one of your allowable characters is present.
The performance would be much improved, however, if you could add a
^,$, or even\bto your regex. For example,which makes sure your match at least grabs the entire word and not just (say) the
B.