包含两个字母和数字以及下划线和破折号的任何字符串的正则表达式代码 [英] Regex code for any string containing BOTH letters AND digits and possibly underscores and dashes

查看:269
本文介绍了包含两个字母和数字以及下划线和破折号的任何字符串的正则表达式代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的正则表达式知识非常有限,但是我试图编写/查找一个表达式,该表达式将捕获文档中的以下字符串类型:

My regex knowledge is pretty limited, but I'm trying to write/find an expression that will capture the following string types in a document:

DO匹配:

  • ADY123
  • AD12ADY
  • 1HGER_2
  • 145-DE-FR2
  • Bicycle1
  • 2自行车
  • 128D
  • 128878P

不匹配:

  • 自行车
  • 183-329-193
  • 3123123

这样的表达可能吗?基本上,它应该找到任何包含字母和数字的字符串,而不管该字符串是短划线还是下划线.我可以使用以下两个正则表达式找到前两个:

Is such an expression possible? Basically, it should find any string containing letters AND digits, regardless of whether the string contains a dash or underscore. I can find the first two using the following two regex:

  • /([[A-Z] [0-9])\ w +/g
  • /([0-9] [A-Z)\ w +/g

但是搜索可能的破折号和连字符会使其变得更加复杂...

But searching for possible dashes and hyphens makes it more complicated...

感谢您提供的任何帮助! :)

Thanks for any help you can provide! :)

更多信息:

我在([A-Z | a-z] [0-9] +-* _ * \ w +)方面取得了一些进展,但是它不能捕获带有多个连字符的字符串.

I've made slight progress with: ([A-Z|a-z][0-9]+-*_*\w+) but it doesn't capture strings with more than one hyphen.

我有一个文档,其中包含很多文本字符串和数字字符串,我不想捕获它们.我想要的是任何产品代码,可以是任何长度的字符串,带有或不带有连字符和下划线,但始终包含至少一位数字和至少一个字母.

I had a document with a lot of text strings and number strings, which I don't want to capture. What I do want is any product code, which could be any length string with or without hyphens and underscores but will always include at least one digit and at least one letter.

推荐答案

您可以在不区分大小写的模式下使用以下表达式:

You can use the following expression with the case-insensitive mode:

\b((?:[a-z]+\S*\d+|\d\S*[a-z]+)[a-z\d_-]*)\b

说明:

\b                   # Assert position at a word boundary
(                    # Beginning of capturing group 1
  (?:                # Beginning of the non-capturing group
    [a-z]+\S*\d+     # Match letters followed by numbers
    |                # OR
    \d+\S*[a-z]+     # Match numbers followed by letters
  )                  # End of the group
  [a-z\d_-]*         # Match letter, digit, '_', or '-' 0 or more times
)                    # End of capturing group 1
\b                   # Assert position at a word boundary

Regex101演示

这篇关于包含两个字母和数字以及下划线和破折号的任何字符串的正则表达式代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆