Reputation: 53
I'm searching for the shortest regex that can matches a string described in a question. I'm also interested in solution where regex matches string where specific character never appears surounded with same character.
This is currently my solution (in this case specific charcter is g):
^.*[^g]{1}g[^g]{1}.*$|^g[^g]{1}.*$|^.*[^g]{1}g$|^g$
I expect that regex matches strings like:aaagaa
, g
, gdddg
, agaagga
, ggaaga
,but doesn't matches: aaagg
,ggaagg
,gg
, ggg
.
Upvotes: 1
Views: 256
Reputation: 785761
You may use this regex to match at least one g
with no adjacent g
:
(?<!g)g(?!g)
RegEx Details:
(?<!g)
: Assert that previous letter is not g
g
: Match a letter g
(?!g)
: Assert that next letter is not g
Upvotes: 2