Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match strings but also have optional group matches

I have the following string:

  • My name is 'Mark' and I live in Spain capital and I like computers programming

I would expect the groups to be:

  • G1: Mark
  • G2: Spain
  • G3: computers

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.

like image 201
LeoScript Avatar asked Sep 15 '25 11:09

LeoScript


2 Answers

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.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

like image 180
Emma Avatar answered Sep 18 '25 10:09

Emma


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

like image 38
Toto Avatar answered Sep 18 '25 09:09

Toto