如何 return 正则表达式匹配子集(可能通过替换模式,但不替换)

How to return regex match subset (perhaps via replacement patterns, but without replacing)

考虑以下几点:

var string = 'http://awesome-site.com/page/#s-in=ascending'
var regex  = /(s-in=)([\w.-]+)/g


var match  = string.match(regex)
console.log(match) 
// this returns: s-in=ascending

// Using replacement patterns, it's possibl to select 
// a subset of the string selected via the regex

var subset = '' + 'new-string'
var match = string.replace(regex, subset)
cosnole.log(match)
// this returns: s-in=new-string

我想弄清楚如何通过正则表达式 return 等号后的字符串(最好是上面示例中的字符串,因为原始字符串 URL 可能相当复杂)。

问题:

如何 return 正则表达式匹配字符串的子集,例如:= 之后的部分?

使用exec方法并像这样获取捕获的组:

var re = /(s-in=)([\w.-]+)/g; 
var str = 'http://awesome-site.com/page/#s-in=ascending';

while ((m = re.exec(str)) !== null) {
    alert(m[2]);
}

在这里,m[2] 将保存值 ascending(第二个捕获组的内容)。

请注意,如果您要匹配文字文本,则不必捕获它(此处为 s-in=)。添加不必要的捕获组意味着不必要的开销。所以,我们最好使用 /s-in=([\w.-]+)/g 正则表达式,并用 m[1].

引用 = 之后的文本

如果您使用 exec,它将 return 一个包含所有捕获组和完整匹配项的数组。

var string = 'http://awesome-site.com/page/#s-in=ascending'
var regex  = /(s-in=)([\w.-]+)/g
regex.exec(string); //returns: ["s-in=ascending", "s-in=", "ascending"]

// below line will create the new object of  RegExp constructor.

var (variable name) = new RegExp('Your Regular expression'),
  
    // now create another variable to hold the substring that will match 
    // for that (created Object)'s method called ".exec()" use by passing "string you want to match" as a parameter.

    (sub string variable name) = (variable name).exec('string that you want to match');

例如

var temp = new RegExp('/(s-in=)([\w.-]+)/g'),
              substring = temp.exec('http://awesome-site.com/page/#s-in=ascending');