修改一个正则表达式,只有[a

这个问题在这里已经有了答案:

  • 如何访问JavaScript正则表达式中的匹配组? 14个答案

  • 截至2018年,Javascript最终支持lookbehind断言,所以一旦它实现,以下应该在最新的浏览器中工作:

    test = "i am sam";
    
    console.log(test.match(/(?<=i'm |i am )[a-zA-Z]+/))

    你可以使用捕获组([a-zA-Z]+)捕捉你的单词:

    I ?['a]m ([a-zA-Z]+)

    这会匹配

    I          # Match I
     ?         # Match an optional white space
    ['a]m      # Match ' or a followed by an m and a whitespace
    (          # Capture in a group
     [a-zA-Z]+ # Match lower or uppercase character one or more times
    )          # Close capturing group
    

    你的话是在第1组。

    var pattern = /I ?['a]m ([a-zA-Z]+)/;
    var strings = [
      "I am good at this",
      "I'm sam"
    ];
    
    for (var i = 0; i < strings.length; i++) {
      console.log(strings[i].match(pattern)[1]);
    }
    链接地址: http://www.djcxy.com/p/76811.html

    上一篇: modify a regex so that only [a

    下一篇: How to extract a string regular expression using java?