在给定的字符串中开发一个模式来匹配字母“b”的任何出现,它不应该跟在字母“a”之后

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

在给定的字符串中开发一个模式来匹配字母“b”的任何出现,它不应该跟在字母“a”之后。

例如:

abc 或 ab 应该 不匹配 , b ba, bb, cba 应该匹配。

我尝试了以下正则表达式:

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

以下输入工作正常:

abba 
dbcd 
bacdba 
bacd 
adfjldb 
dkfjb
abdfdsba

但是好像我在一行中给出了输入,比如:

ab ba abdkfjdk bacdk dkekfba

与字词不符

如果要匹配 任何不在 "a" 之后的字母“b”。即,"b" 不应该在 "a" 之后,但是 "a" 可以在 "b 之后你可以使用这个使用 negative lookbehind:

(?<!a)b

说明

  • 负面回顾(?<!
  • 断言后面的不是a
  • 关闭负面回顾)
  • 匹配b

您的问题描述与您的样本不符。你说的问题是:

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

那就是

 [^a](b)

See here,所需的匹配项为绿色。

然而你的样本暗示了一个不同的问题。他们暗示正确的问题描述必须是:

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

这将是

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

See here,所需的匹配项为绿色。