tags:

views:

130

answers:

4

I guess I'm getting really weak in logic.

I need to write a regular expression which matches everything except www. It should match wwwd, abcd and everything else, just not www. (Oh God, please, it shouldn't be very easy).

I'm using Ruby language's implementation of regular expression.

UPDATE: I need to use regular expression and not just text != 'www' because it is the way API is designed. It expects a pattern as argument and not the result.

+9  A: 

Why regex? Isn't text != "www" enough?

Here it is nonetheless (uses look-ahead): ^(?!www$).*

soulmerge
This match empty string on non "www" string, not the whole word.
Dejw
@Dejw: Thx, fixed
soulmerge
+4  A: 

This is a plain vanilla regex. There are fancier things you can do with negative assertions in certain dialects.

^(.|..|[^w]..|.[^w].|..[^w]|.....*)$

In English:

You want something that's exactly one character, exactly two characters, exactly three characters where at least one of those 3 is not a w, or more than 3 characters long.

Laurence Gonsalves
+1 nice approach. Just one superfluous period in last group.
soulmerge
@Gumbo: Why? `.[^w].` matches `wow`.
soulmerge
@soulmerge: the last period isn't superfluous (assuming you're saying it shouldn't be five periods). It's four periods (....) plus zero or more additional characters (.*) for a total of five periods. It could also be specified as "....+".
Bryan Oakley
Ah, I thought it *was* a plus at the end. I guess seeing 5 periods brought up the confusion (I was expecting *4* or more letters).
soulmerge
A: 

Same general idea as Laurence Gonsalves(*), but it seems to me one could say ^.$|^..$|^....+$|.*[^w].* That is, 1 or 2 or more than 3 characters between start and end, or any number containing a non-w.

(*) I really meant this to be a comment on his answer, but accidentally posted it as my own answer. I guess I'll just leave it here.

Tim Goodman
A: 

Just another approach

^.{0,2}([^w].*|.{4,})?$
Diadistis