开发者

Matching all words except one

Say I have a sentence:

I am a good buy and bad boy too

How to select every word except boy in this sentence using reg开发者_如何学编程ular expression ?


You can use negative look behind:

\w+\b(?<!\bboy)

Or negative look ahead since not all support negative look behind

(?!boy\b)\b\w+

You can read about negative look ahead here


Try:

\b(?!boy\b).*?\b

which means:

  • Zero width word break (\b)
  • That isn't followed by "boy" and another word break;
  • followed by any characters in a non-greedy way;
  • Up until another word break.

Note: the word break matches the start of the string, the end of the string and any transition from word (number, letter or underscore) to non-word character or vice versa.


/\b(?!boy)\S+/g


If you use "boy" as splitter, you would get remaining parts. You could use those as selection keys.

>>> re.split("boy","I am a good buy and bad boy too")
['I am a good buy and bad ', ' too']


Substitute boy to nothing... in Perl that would be:

s/boy //g


I tested the following with http://regex101.com:

\b(?!boy)\S+|\w*\b$

This provides the list of all words delimited by spaces, but excludes only the word "boy" as asked.


As alternative, if possessive quantifiers are available, you can use;

\w++(?<!boy)

It takes generally less steps than using world boundaries.


Which language? Why do you want to use a regex?

answer = yourString.Replace( "boy", "" );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜