[英]Regex to match words ending with the letter a followed by how many a's there were at the end of the word
我们只想匹配以一个或两个 a 结尾的单词。 所以我们不会匹配aaa3。 我们也不希望匹配数字不匹配的单词,例如 hea2
以下是一些可能具有匹配项的示例字符串:
Iaa2 ama1 from the uka1, Iaa2 like the uka1 very much
Dog isa1 aaa2 pet animal
我正在寻找的比赛:
Iaa2 ama1 uka1 Iaa2 uka1
isa1 aaa2
谢谢!
\b
匹配单词边界。 \w
匹配任何单词字符(字母、数字、下划线)。 由于您的话只能以“a1”或“aa2”结尾,因此交替可以实现目标:
/\b\w*(?:a1|aa2)\b/g
例如
input.match(/\b\w*(?:a1|aa2)\b/g)
显然你不想禁止aaa2
,因为它也会匹配aaa3
。 这是一个解决方案,它匹配以字母a
结尾的单词,后跟一个数字,该数字表示找到的字母a
的数量。 我还添加了aaa3
,如果需要,您可以添加更多。
const input = `Iaa2 ama1 from the uka1, Iaa2 like the uka1 very much Dog isa1 aaa2 pet animal`; const matches = input.match(/\w+(?:a1|aa2|aaa3)\b/g); console.log(matches)
Output:
"Iaa2",
"ama1",
"uka1",
"Iaa2",
"uka1",
"isa1",
"aaa2"
]
正则解释:
\w+
-- 1+ 个单词字符(?:
-- 非捕获组开始(逻辑或)
a1
-- 文字a1
|
- 或者
aa2
-- 文字aa2
|
- 或者
aaa3
-- 文字aaa3
(如果需要,冲洗并重复))
-- 非捕获组结束\b
-- 单词边界g
标志以匹配多次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.