Search code examples
regexregexp-replace

regex to extract substring for special cases


I have a scenario where i want to extract some substring based on following condition.

  1. search for any pattern myvalue=123& , extract myvalue=123
  2. If the "myvalue" present at end of the line without "&", extract myvalue=123

for ex:

The string is abcdmyvalue=123&xyz => the it should return  myvalue=123
The string is abcdmyvalue=123 => the it should return  myvalue=123

for first scenario it is working for me with following regex - myvalue=(.?(?=[&,""])) I am looking for how to modify this regex to include my second scenario as well. I am using https://regex101.com/ to test this.
Thanks in Advace!


Solution

  • Some notes about the pattern that you tried

    • if you want to only match, you can omit the capture group
    • e* matches 0+ times an e char
    • the part .*?(?=[&,""]) matches as least chars until it can assert eiter & , or " to the right, so the positive lookahead expects a single char to the right to be present

    You could shorten the pattern to a match only, using a negated character class that matches 0+ times any character except a whitespace char or &

    myvalue=[^&\s]*
    

    Regex demo