tags:

views:

106

answers:

6

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 regular expression ?

+5  A: 

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

answer = yourString.Replace( "boy", "" );
tanascius
-1 This is a silly answer.
cletus
Silly because? The spec is not clear and this solution matches one of the interpretations.
Grzegorz Oledzki
Note the OP said "word". This will match partials. So if you wanted to ignore "top" and you did this replace you'd also hit "stopped". So this answer is silly because it doesn't an *unnecessary* replacement that doesn't solve the problem, ignores the issue of word boundaries and just introduces more problems.
cletus
It doesn't use a Regex - that seems to be a problem for you. In my opinion you do not have to use a Regex in all cases. Here is a solution, that does not. You can find wordboundaries by including spaces. This answer might be helpful to the OP since it introduces a new possibility without Regex. But the OP is free to accept whatever answer fits best to his requirements.
tanascius
Regex or non-regex, I don't care so long as it works. Simple string replacement when looking for **words** clearly does not.
cletus
+1  A: 

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

s/boy //g
Niels Castle
Even better, remove `boy ` (i.e. boy+space)
kemp
Quite right, I updated the answer accordingly...
Niels Castle
+3  A: 

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

Jeremy Seekamp
correct answer checked here http://www.gskinner.com/RegExr/
pokrate
+1  A: 
/\b(?!boy)\S+/g
KennyTM
+4  A: 

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.

cletus
Wrong answer, plainly not selecting anything at all.
pokrate
+2  A: 

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']
S.Mark