Home > Net >  regex (regular expression): parse the optional end of the string if it exists
regex (regular expression): parse the optional end of the string if it exists

Time:01-22

Please help me to find the end of the string and parse it.

I have the string like this "Some words" and "Some another words||MyTag". Please help me with regex to check any of this strings. But in the second case please extract "MyTag". So please make two groups: "Some words" or "Some another words" and MyTag or empty string.

I tried "^([\W\w] )(?:||(.*))?" but without any success.

CodePudding user response:

You can create 2 capture groups:

^(. ?)(?:\|\|(. ))?$
  • ^ Start of string
  • (. ?) Capture group 1 Match any character except newlines as least as possible
  • (?: Non capture group
    • \|\|(. ) Match || and capture 1 chars in group 2
  • )? Close non capture group and make it optional
  • $ End of string

If the second part is not present, then there will be no group 2 value.

Regex demo

You might also consider to split on ||


Another option without a non greedy dot is to not allow matching |, only when it is not directly followed by | using a negative lookahead.

^([^\r\n|]*(?:\|(?!\|)[^\r\n|]*)*)(?:\|\|(. ))?$

Regex demo

  •  Tags:  
  • Related