In Ruby, I want to have a regex match either of two expressions with a single group in the result. I want the following results:
regex = /you tell me/
regex.match(%|My name is "Peter"|)[1]
=> "Peter"
regex.match(%|My name is 'Peter'|)[1]
=> "Peter"
Note that I want the 1st group to refer to just Peter with no quotes, and I want there to be exactly one group matched in either case. Just as an example, this would match the first case (only):
/^My name is "([^"]*)"$/
I’d like something similar to that. I happen to be using this for cucumber testing.
This regex might work for you
It matches exactly one group. But it also allows unbalanced quotes, like
'Peter"If you want to match only balanced quotes, then you can’t do it with a single group (I’m afraid).
Anyhow, here’s my take:
It matches two groups and “Peter” is in the second one.