Home > Mobile >  Problem with regular expression with 2 capture group, one is optional
Problem with regular expression with 2 capture group, one is optional

Time:10-18

I'm struggling to write the correct regex to match the data below. I want to capture the "Focus Terminal" and its optional parameter "NYET". How can I re-write my incorrect regex?

user:\/\/(.*)(?:=(.* ))?

I also tried and failed:

user:\/\/(.*)=?(?:(.* ))?

Sample Data

*   user://Focus Terminal=NYET
*   user://Focus Terminal

CodePudding user response:

You can use

user:\/\/(.*?)(?:=(.*))?$

See the regex demo.

Details:

  • user:\/\/ - a user:// string
  • (.*?) - Group 1: any zero or more chars other than line break chars as few as possible
  • (?:=(.*))? - an optional non-capturing group that matches a = and then captures into Group 2 any zero or more chars other than line break chars as many as possible
  • $ - end of string.

CodePudding user response:

As an alternative you might use a negated character class excluding matching a newline or equals sign for the first capture group.

user:\/\/([^=\n]*)(?:=(.*))?

Explanation

  • user:\/\/ Match user://
  • ([^=\n]*) Capture group 1, match optional chars other than = or a newline
  • (?:=(.*))? Optionally match = and capture the rest of the line in group 2

Regex demo

  • Related