Reputation: 36151
In the construction of an interactive form, I need to parse some regex submitted by the user, find every match captures in each regex and get their index (where the capture group begins) to modify the original string (let's say to add some <strong>
tag around the capture for example).
At the end I want to be able to modify ip:(.+);port:(\d+)
into ip:<strong>(.+)</strong>;port:<strong>(\d+)</strong>
for example.
Currently I have this little piece of code:
// Called somewhere after user entered every regex he wants
$('input.regex').each(function () {
pattern = $(this).val(); // for non jQuery guys: just returns the content of the input
captures = pattern.match(/(\([^\(\)]+\))/g);
for(idx in captures) {
console.log(captures[idx]);
}
});
This returns me every capturing group found (admit the user can't type subgroups... yeah the regex can give a little headache already :-)) When I run it on some examples I get what I want for the moment:
ip:(.+);port:(\d+)
, outputs (.+)
and (\d+)
ip:(?P<sourceip>[\d\.]);port:(\d{2,5})
, outputs (?P<sourceip>[\d\.])
and (\d{2,5})
Now what I wanted is to get the index of the beginning of each capture. I know there's indexOf, but I can have the same capture several times. For example:
id1:(\d+);id2:(\d+)
currently outputs (\d+)
and (\d+)
. Easy to get the first index but the second one...Is there any possibility to get a structure similar to this: [{'match': '(\d+)', 'index': 4}, {'match': '(\d+)', 'index': 14}]
? I could do this with some string manipulation but I want to know if there's a simplier (and cleaner) way.
Upvotes: 2
Views: 380
Reputation: 1004
I would use RexExp.exec() for this. It operates on a RexExp and matches it against a string, but most importantly it returns an array of each match which can be iterates through like this.
var match; //Match object.
var matches = []; //Matches return, Array filled with match records.
var regex = "..."; //Current Regex.
var string = "..."; //Current String.
while((match = regex.exec(string)) !== null){
var matchRecord = {};
matchRecord.match = regex;
matchRecord.index = match.index; //Might want to increment by 1 to make Human Readable?
matches.push(matchRecord);
}
Note: More info about regexp.exec here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
Upvotes: 2