修改正则表达式,以便只捕获 [a-zA-Z]
modify a regex so that only [a-zA-Z] is captured
我有以下正则表达式:
/i'm [a-zA-Z]|i am [a-zA-Z]*/i
它在检测短语何时与正则表达式匹配方面起作用,但我专门尝试捕获 [a-zA-Z]
部分。
例如:
"I'm sam" // -> sam
I am good at this // -> good
告诉我这个问题是否需要改进。
提前致谢! ^^
截至 2018 年,Javascript 终于支持后向断言,因此一旦实施,以下内容应该可以在最新的浏览器中使用:
test = "i am sam";
console.log(test.match(/(?<=i'm |i am )[a-zA-Z]+/))
UPD:在撰写本文时,只有 Chrome 可以做到这一点,所以这个答案将在几个月后有效。与此同时,
test = "i am sam";
console.log(test.match(/(?:i'm |i am )([a-zA-Z]+)/)[1])
您可以使用捕获组来捕获您的话 ([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]);
}
我有以下正则表达式:
/i'm [a-zA-Z]|i am [a-zA-Z]*/i
它在检测短语何时与正则表达式匹配方面起作用,但我专门尝试捕获 [a-zA-Z]
部分。
例如:
"I'm sam" // -> sam
I am good at this // -> good
告诉我这个问题是否需要改进。 提前致谢! ^^
截至 2018 年,Javascript 终于支持后向断言,因此一旦实施,以下内容应该可以在最新的浏览器中使用:
test = "i am sam";
console.log(test.match(/(?<=i'm |i am )[a-zA-Z]+/))
UPD:在撰写本文时,只有 Chrome 可以做到这一点,所以这个答案将在几个月后有效。与此同时,
test = "i am sam";
console.log(test.match(/(?:i'm |i am )([a-zA-Z]+)/)[1])
您可以使用捕获组来捕获您的话 ([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]);
}