views:

59

answers:

1

I want to be able to detect/pick apart strings like :

tickets at entrance per person
ballons pp
tree planting

i.e. a description followed by an optional "pp" or "per person"

I try (.+)\s+(per person|pp) and that works; but the pp|per person suffix is then not optional.

I try (.+)\s+(per person|pp)? or (.+)\s+(per person|pp){0,1} to make it optional, but then I get "undefined for the second capture group". Curiously the first capture group contains the "per":

matches: 0: (tickets at entrance per )
1: (tickets at entrance per)
2: (undefined)

(tested via http://www.regextester.com/ online regex tester)

What am I doing wrong with that second capture group ?

+1  A: 

You can try this :

^(.+?)\s*(per person|pp|)$

You can read it like this :

Starts with  
 (any characters but at least one and not in greedy mode)
 any space-characters
 ("per person" or "pp" or nothing)
end
Colin Hebert
Beautiful: works. Thank you !
Turns out this isn't quite what is needed after all. The required "any space character" in the middle there wont be present when the string does not contain the "pp|per person" suffix.
I spoke too soon. I had tried^(.+)\s+(per person|pp|)$which does work (note the \s+ vs the suggested \s*), but requires a trailing space if the per person|pp is not the suffixSo for example:"tree planting"will not be matched by this regex, although"tree planting "(note the trailing space) will be. The regex you suggested:^(.+)\s*(per person|pp|)$Does not work because the first group is greedy and returns the whole string, eg. "balloons per person"returns 1: (balloons per person)2: ()instead of what I want which is:1: (balloons)2: (per person)
aha: make the first group non greedy: (.+?) does the trick
Updated with an ungreedy "+" :)
Colin Hebert