0

In a given string develop a pattern to match any occurrence of letter “b” , Where it should not follow letter “a”.

For example:

abc or ab should not match, b ba, bb, cba should match.

I tried the following regex:

**/(?!.*ab)(?=.*b)^(\w+)$/**

The foll inputs are working fine:

abba 
dbcd 
bacdba 
bacd 
adfjldb 
dkfjb
abdfdsba

but where as if I give the input in a single line like:

ab ba abdkfjdk bacdk dkekfba

it is not matching the words.

Bk.Neo
  • 61
  • 1
  • 7

2 Answers2

0

If you want to match any occurrence of letter “b” which is not after "a". i.e., "b" should not be after "a", but "a" can be after "b you could use this regex which uses a negative lookbehind:

(?<!a)b

Explanation

  • A negative lookbehind (?<!
  • Which asserts that what is behind is not a
  • Close negative lookbehind )
  • Match b
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • In a given string develop a pattern to match any occurrence of letter “b” which is not after "a". i.e., "b" should not be after "a", but "a" can be after "b" – Bk.Neo Jan 11 '18 at 12:20
0

Your problem description doesn't match your samples. You say the problem is:

In a given string, develop a pattern to match any occurrence of letter “b”, where "b" is not not followed the letter “a”.

And that would simply be

 [^a](b)

See here, the desired matches are in green.

Yet your samples imply a different problem. They imply that the correct problem description must be:

In a given string, develop a pattern to match any word containing the letter "b", unless that "b" follows the letter "a".

And this would be

 \w*ab\w*|(\w*b\w*)

See here, the desired matches are in green.

Mecki
  • 125,244
  • 33
  • 244
  • 253
  • Thanks Mecki, i needed the second one "In a given string, develop a pattern to match any word containing the letter "b", unless that "b" follows the letter "a"." – Bk.Neo Jan 12 '18 at 06:52