首页 > 解决方案 > 匹配具有唯一数字的字母数字单词(NOT NUMERIC-ONLY words)

问题描述

使用正则表达式,我只想选择以下单词

我对正则表达式不是很擅长,但到目前为止,我已经尝试过[^\d\s]*(\d+)(?!.*\1),这让我无法接近所需的输出:(

以下是输入字符串:

I would like abc123 to match but not 123.
ab12s should also match
Only number-words like 1234 should not match
Words containing same numbers like ab22s should not match
234 should not match
hel1lo2haha3hoho4
hel1lo2haha3hoho3

预期比赛:

abc123
ab12s
hel1lo2haha3hoho4

标签: javascriptregex

解决方案


您可以使用

\b(?=\d*[a-z])(?=[a-z]*\d)(?:[a-z]|(\d)(?!\w*\1))+\b

https://regex101.com/r/TimjdW/3

在单词边界处锚定模式的开始和结束\b,然后:

  • (?=\d*[a-z])- 前瞻单词中某处的字母字符
  • (?=[a-z]*\d)- 提前查找单词中的某个数字
  • (?:[a-z]|(\d)(?!\w*\1))+反复匹配:
    • [a-z]- 任何字母字符,或
    • (\d)(?!\w*\1)- 在同一个单词中不再出现的数字

推荐阅读