Tuesday, March 27, 2018

javascript - Regex Group Capture




I have a standard email which I am looking to extract certain details from.



Amongst the email are lines like so:



Name: John Smith


So to simulate this I have the following JavaScript:





var str = "
Name: John Smith
";
var re = /\Name\s*:\<\/strong>\s*([^\<]*)/g
match = re.exec(str);
while (match != null) {
console.log(match[0]);
match = re.exec(str);
}





This only comes out with one result, which is:



Name: John Smith


I was hoping to get the capture group ([^\<]*) which in this example would be John Smith



What am I missing here?


Answer



Capture groups are provided in the match array starting at index 1:





var str = "
Name: John Smith
";
var re = /\Name\s*:\<\/strong>\s*([^\<]*)/g
match = re.exec(str);
while (match != null) {
console.log(match[1]); // <====
match = re.exec(str);
}





Index 0 contains the whole match.



On modern JavaScript engines, you could also use named capture groups ((?...), which you can access via match.groups.theName:





var str = "
Name: John Smith
";
var re = /\Name\s*:\<\/strong>\s*(?[^\<]*)/g
// ---------------------------------------^^^^^^^
match = re.exec(str);
while (match != null) {
console.log(match.groups.name); // <====
match = re.exec(str);
}




No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...