[javascript][regex]javascript簡易使用regular expression取值的範例

  • 94
  • 0

[javascript][regex]javascript簡易使用regular expression取值的範例

javascript:

var myString = "radioYNSign15";
var myRegexp = new RegExp("(?<CharGrp>radioYNSign)(?<NumberGrp>\\d+)", "g");
var match = myRegexp.exec(myString);
console.log(match); 

//未具名的match
console.log(match[0]);//整個match到的字串
console.log(match[1]);//match到的第[1]個字串
console.log(match[2]);//match到的第[2]個字串

//具名的match
console.log(match.groups.CharGrp);
console.log(match.groups.NumberGrp);

output:



大概是這樣,給自己以及所有想要快速使用regular expression取value的人

參考資料:
https://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular-expression