How do you access the matched groups in a JavaScript regular expression ?

How do you access the matched groups in a JavaScript regular expression ?

Asked on December 15, 2018 in Regex.
Add Comment


  • 3 Answer(s)

    Try this code for accessing groups of javaScript regular expression :

    var myString = "something format_abc";
    var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
    var match = myRegexp.exec(myString);
    console.log(match[1]); // abc
    

    There are multiple matches you can perform over them by this code:

    var myString = "something format_abc";
    var myRegexp = /(?:^|\s)format_(.*?)(?:\s|$)/g;
    match = myRegexp.exec(myString);
    while (match != null) {
      // matched text: match[0]
      // match start: match.index
      //  capturing group n: match[n]
      console.log(match[0])
      match = myRegexp.exec(myString);
    }
    

     

    Answered on December 15, 2018.
    Add Comment

    In this method you can get the n​th capturing group for each match:

    function getMatches(string, regex, index) {
      index || (index = 1); // default to the first capturing group
      var matches = [];
      var match;
      while (match = regex.exec(string)) {
        matches.push(match[index]);
      }
      return matches;
    }
     
    // Example :
    var myString = 'something format_abc something format_def something format_ghi';
    var myRegEx = /(?:^|\s)format_(.*?)(?:\s|$)/g;
     
    // Get an array containing the first capturing group for every match
    var matches = getMatches(myString, myRegEx, 1);
     
    // Log results
    document.write(matches.length + ' matches found: ' + JSON.stringify(matches))
    console.log(matches);
    
    Answered on December 15, 2018.
    Add Comment

    Try this very simple method:

    var myString = "something format_abc";
    var arr = myString.match(/\bformat_(.*?)\b/);
    console.log(arr[0] + " " + arr[1]);
    

    In above code  \b is  not exactly the same thing. It works on –format_foo/, but does not work on format_a_b But it is a alternative to your expression. it will call  the match groups in a JavaScript regular expression.

    Answered on December 15, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.