Home > Back-end >  Extract string when from dynamic input where part of the string may not exists
Extract string when from dynamic input where part of the string may not exists

Time:10-28

Lets assume I have a string

Abc=cde&efg

This formula gives me three groups

(.*=)(.*)(&.*)

But what if input string is dynamic and &efg may exists or not?
When it doesn't above formula will give me nothing. I need to use this regex in golang and I would like to do it with one regex (if it is possible) without splitting string with &.

CodePudding user response:

You can use

^(.*=)(.*?)(&.*)?$

See the regex demo.

Details:

  • ^ - start of string
  • (.*=) - Group 1: any zero or more chars other than line break chars as many as possible and then a = char
  • (.*?) - Group 2: any zero or more chars other than line break chars as few as possible
  • (&.*)? - Group 3 (optional): a & and then any zero or more chars other than line break chars as many as possible
  • $ - end of string.
  • Related