Reputation: 1878
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?
Upvotes: 1
Views: 3096
Reputation: 784998
As per your comment $$
will always be there. If that's the case then you can simply use:
/\$\$([bBWw]?c?m?\d*)/
Upvotes: 0
Reputation: 56905
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.
/(?=[BbWwcm0-9])([bBWw])?(c?)m?([0-9]*)/
The performance would be much improved, however, if you could add a ^
, $
, or even \b
to your regex. For example,
/\b(?=[BbWwcm0-9])([bBWw])?(c?)m?([0-9]*)\b/
which makes sure your match at least grabs the entire word and not just (say) the B
.
Upvotes: 3
Reputation: 5264
Sure tell it to look for the string inside of the $$ and the space using lookahead and lookbehind.
Upvotes: 0