I have the following string:
I would expect the groups to be:
being the case that "capital" can be "state" or some other fixed option or empty, the same applies for "programming"
I want to have portions that are optional so all the matches I would expect are:
My name is 'Mark' and I live in Spain capital and I like computers programming
My name is 'Mark' and I live in Spain capital and I like computers
My name is 'Mark' and I live in Spain capital
My name is 'Mark' and I live in Spain
I have so far used the following regex:
My name is '([^']+?)' and I live in ([^']+?)(?: capital|)(?: and I like ([^']+?)|)(?: programming| reading|)
I use it in SpecFlow for automation purposes and IT WORKS WELL, But when I use it in any regex tester it does not look well: https://regex101.com/r/Ro0rHP/1
Also it somehow makes the UI integration between Visual Studio 2019 and SpecFlow not work properly for the next steps after that one.
Now, I'm looking for probably some alternatives to this Regex, one that works in regex testers, I fought this for a while.
I'm guessing that you're trying to write an expression that'd maybe look like,
My name is '([^']+)' and I live in (.+?)(?:$| capital$| capital and I like (.+?)(?: programming|$))
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
jex.im visualizes regular expressions:
Expression like (?: capital|)
is better writen (?: capital)?
.
I'd use:
My name is '([^']+)' and I live in (\S+)(?: capital)?(?: and I like (\S+))?(?: programming| reading)?
Explanation:
My name is # literally
'([^']+)' # group 1, 1 or more non quote between quotes
and I live in # literally
(\S+) # group 2, 1 or more non space
(?: capital)? # non capture group, optional
(?: # non capture group
and I like # literally
(\S+) # group 3, 1 or more non space
)? # end group, optional
(?: programming| reading)? # non capture group, optional
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With