首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用正则表达式检测数字和字母的组合

如何用正则表达式检测数字和字母的组合
EN

Stack Overflow用户
提问于 2022-05-16 21:12:55
回答 2查看 54关注 0票数 -2

我只需要从一个只有数字和字母组合存在的句子中检测单词。

我正在使用这个https://regex101.com/r/eSlu2I/1 ^[a-zA-Z0-9]*正则表达式。

在这里,最后两个应该被排除在外。有人能帮我吗?

EN

回答 2

Stack Overflow用户

发布于 2022-05-16 21:14:25

使用

代码语言:javascript
复制
^(?![a-zA-Z]+\b)[a-zA-Z0-9]*

正则证明

解释

代码语言:javascript
复制
NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    [a-zA-Z]+                any character of: 'a' to 'z', 'A' to 'Z'
                             (1 or more times (matching the most
                             amount possible))
--------------------------------------------------------------------------------
    \b                       the boundary between a word char (\w)
                             and something that is not a word char
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  [a-zA-Z0-9]*             any character of: 'a' to 'z', 'A' to 'Z',
                           '0' to '9' (0 or more times (matching the
                           most amount possible)) 
票数 0
EN

Stack Overflow用户

发布于 2022-05-16 21:25:22

您可以使用以下正则表达式:

代码语言:javascript
复制
\w*\d\w*

解释:

  • \w*:字母数字字符的可选组合
  • \d:数字
  • \w*:字母数字字符的可选组合

试试吧,这里

编辑:如果需要显示至少一个字母和数字,则可以使用以下regex:

代码语言:javascript
复制
\w*(\d[A-Za-z]|[A-Za-z]\d)\w*

解释:

  • \w*:字母数字字符的可选组合
  • (\d[A-Za-z]|[A-Za-z]\d)
    • \d[A-Za-z]|:数字+字母字符或
    • [A-Za-z]\d:字母+数字

  • \w*:字母数字字符的可选组合
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72265691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档