cluster_master
cluster_master

Reputation: 53

How to match a string with regex where specific character appears at least once so that the first neighbours characters are different from it?

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

Answers (1)

anubhava
anubhava

Reputation: 785761

You may use this regex to match at least one g with no adjacent g:

(?<!g)g(?!g)

RegEx Demo

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

Related Questions