javascript - Match every occurences with regex and get their indexes in string -
in construction of interactive form, need parse regex submitted user, find every match captures in each regex , index (where capture group begins) modify original string (let's add <strong>
tag around capture example).
@ end want able modify ip:(.+);port:(\d+)
ip:<strong>(.+)</strong>;port:<strong>(\d+)</strong>
example.
currently have little piece of code:
// called somewhere after user entered every regex wants $('input.regex').each(function () { pattern = $(this).val(); // non jquery guys: returns content of input captures = pattern.match(/(\([^\(\)]+\))/g); for(idx in captures) { console.log(captures[idx]); } });
this returns me every capturing group found (admit user can't type subgroups... yeah regex can give little headache :-)) when run on examples want moment:
- on
ip:(.+);port:(\d+)
, outputs(.+)
,(\d+)
- on
ip:(?p<sourceip>[\d\.]);port:(\d{2,5})
, outputs(?p<sourceip>[\d\.])
,(\d{2,5})
now wanted index of beginning of each capture. know there's indexof, can have same capture several times. example:
id1:(\d+);id2:(\d+)
outputs(\d+)
,(\d+)
. easy first index second one...
is there possibility structure similar this: [{'match': '(\d+)', 'index': 4}, {'match': '(\d+)', 'index': 14}]
? string manipulation want know if there's simplier (and cleaner) way.
i use rexexp.exec() this. operates on rexexp , matches against string, importantly returns array of each match can iterates through this.
var match; //match object. var matches = []; //matches return, array filled 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 increment 1 make human readable? matches.push(matchrecord); }
note: more info regexp.exec here: https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/regexp/exec
Comments
Post a Comment