I am trying to build a regex that should match for example.
b
abab
babab
but not
bb
babb
aaaba
abaaba
At the moment I have a(b)|b(a) and it is working for abab. I am missing the first and last letter, for example b or babab.
So I need to specify a alone or b alone or a letter at the end of a word (if the letter before it isn’t itself). But I can’t figure out how to do that.
I am using http://www.rexv.org/ (Perl PCRE) to try it.
Thanks guys but i forgot to mention:
An empty string can also be matched,
and i can only use the following
* ? +
|
()
.
Thanks guys!,
i suppose it isn’t possible without being able to specify beginning and end of the string to work correctly at http://www.rexv.org/
Try something like this:
Explained:
I include the subgroups as non-capturing with the leading
(?:using a full-capturing group around the entire regex. This will make sure to return you only the full-strings that match instead of the noise of each sub-group.The caveat to this approach is that an “empty” string will also match.
UPDATE (limited set of characters)
Your limited-set of characters will still work with my pattern above, however, we’ll need to drop the non-matching group portion (
?:). The regex will end up as:The caveat mentioned above is that it will also match an empty string, however, this appears to be what you need so we can add that to the bonus-list!
A slight issue with the set of characters you’re allowed to use is that you aren’t allowed to use the
^and$characters which indicate the start and end of a string, respectively. The problem with this is that, any sub-pattern that is matched (regardless of the regex you use) will flag the input as valid. I’m assuming that this is accounted for though.