0

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 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

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 suffix So 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)
Updated with an ungreedy "+" :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.