Javascript RegExp -如何匹配X只有当A在X之前和B在X之后

Javascript RegExp - how to match X only when A is before X and B is after X

本文关键字:之后 RegExp 何匹配 Javascript      更新时间:2023-09-26

给定字符串"AXB",我只希望在A在X之前,B在X之后匹配X,但是我不希望在返回的匹配中出现A或B。

我明白,对于B,它可以这样做:/X(?=B)/但我不确定是否有类似的方式这样做A(比赛前)?

谢谢。

使用捕获组捕获值,然后引用组#1访问匹配。

/A(X)B/

的例子:

console.log('AXB'.match(/A(X)B/)[1]); //=> 'X'

像这样:

var the_captures = []; 
var yourString = 'your_test_string'
var myregex = /A(X)B/g;
var thematch = myregex.exec(yourString);
while (thematch != null) {
    // add it to array of captures
    the_captures.push(thematch[1]);
    document.write(thematch[1],"<br />");    
    // match the next one
    thematch = myregex.exec(yourString);
}

  • A匹配文字A
  • (X)匹配X并捕获到组1
  • B匹配B
  • 脚本返回组1:thematch[1]

在其他语言

JavaScript没有查找或'K。在支持这些的语言中,您可以直接匹配没有捕获组的X:

  • A'KX(?=B)(使用向前看和'K,这告诉引擎放弃匹配到目前为止它返回的最终匹配)
  • (?<=A)X(?=B)(使用后向和前向断言)