tags:

views:

146

answers:

5

The following regex should be for Do Dollars Dollar or #do #Dollars or #Dollar but not for Doblabla (which it currently is) etc..

/^@(?P<name>\w+) (?P<amount>\d+) [#]?Do(?:llars?)?/i

How do I change that? So that it no longer matches on Dogfood and Dogs etc...

Update 3: Not Solved Afterall:

 /^@(?P<name>\w+) (?P<amount>\d+) [#]?(do(?:llars?|s))/i

The following does not match:

@name 2 do

Any thoughts?

My second question is how do I then allow it to also match to: Dox and #Dox

So in the end I want it to match to

@name 2 #do
@name 2 do
@name 2 #dollars
@name 2 dollars
@name 1 dollar
@name 1 #dollar
@name 2 dox
@name 2 #dox

and nothing else.

Thank you very much!

Ice

+2  A: 

If I'm not mistaken, (?:llars?)? suggests that this will match anything starting with do and not care what is after it since it is optional.

Add a $ to the end to enforce that the string ends in do or dollars.

Ryan Graham
When I add an $ to the end of the expression that excludes source like@name 5 dollars because blabla Hence that hasn't worked - or am I placing it wrong?
That example isn't on your list. You should clarify in the question that other words may follow.
Ryan Graham
+1  A: 

Use the $ anchor to mark the end of the line and the | operator for alternatives alt-1|alt-2|…:

 /^@(?P<name>\w+) (?P<amount>\d+) #?(do(?:llars?|x)?)$/i
Gumbo
+1  A: 

I found the answer after some more tries on Regexp.net

[#]?(do(?:llars?))
This won't match "@name 2 do"
Greg
Oh no! You're right - back to square 1
+2  A: 

This should do it for you:

/^@(?P<name>\w+) (?P<amount>\d+) #?Do(?:llars?|x)(?:\s|$)/i

This matches the name and amount followed by an optional # then "do" then "llar", "llars", whitespace or the end of the string.

Greg
I had an extra "?" in at the end which I have removed so please make sure it ends $)/i when you test
Greg
Edited again to match "dox" and not match "dollarsfoo" (but still match "dollars" or "dollars foo")
Greg
Thank you - this is perfect! I really appreciate that you took the time to help me with this. It's teaching me a lot about regex's that the cheat sheet hasn't ;)
A: 

Maybe I'm not understanding totally, but your regex looks overly complex to me. What's wrong with doing it like this?

/^@name [12] #?do(llar|llars|x)?$/

Edit: after reading through the comments it sounds like you have other requirements that you didn't put in the question. Editing those in so we have an actual complete problem to work on would make things a lot easier.

Chad Birch