Home > other >  regex to extract substring for special cases
regex to extract substring for special cases

Time:11-02

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!

CodePudding user response:

function regex(data) {
var test = data.match(/=(.*)&/);
if (test === null) {
return data.split('=')[1]
} else {
return test[1]
}
}

console.log(regex('abcdmyvalue=123&3e')); //123
console.log(regex('abcdmyvalue=123')); //123

here is your working code if there is no & at end of string it will have null and will go else block there we can simply split the string and get the value, If & is present at the end of string then regex will simply extract the value between = and &

if you want to use existing regex then you can do it like that

var test = data1.match(/=(.*)&|=(.*)/)

const result = test[1] ? test[1] : test[2];
console.log(result);

CodePudding user response:

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

  • Related