在JavaScript中工作,我有字符串可能包含以"@"为前缀的单词。字符串可能如下所示@one two @three
。我想要一个正则表达式,它可以找到以"@"为前缀的单词,但我不想包含"@"本身。
我创建了一个看起来像这样的正则表达式/@(w+)/g
但是当我将其与我的字符串匹配时,确实包含"@"。这是为什么呢?我假设如果我想包含它,那么"@"将在捕获括号内,如下所示/(@w+)/g
var s = '@one two @three'
var matches = s.match(/@(w+)/g)
// matches is now [ '@one', '@three' ] but I want [ 'one', 'three' ]
请注意,根据我目前得到的结果,获取我想要的数组当然没有问题,我可以删除每个字符串的第一个字符。但我想知道的是:
是否可以更改我的正则表达式以获得所需的结果?和:为什么结果中包含捕获括号之外的字符?我发现只应包含括号内的字符是直观的。
访问第一个捕获组
var re = /@(w+)/gm;
var str = '@one two @three';
var m;
while ((m = re.exec(str)) !== null) {
print(m[1]);
}
Ideone 演示
JS演示
var re = /@(w+)/;
var arr = ['@one', 'two', '@three'];
arr.forEach(function(str) {
if (str.match(re))
document.writeln(str.match(re)[1] + '<br>');
});