简体   繁体   English

用正则表达式匹配交替字母数字字符

[英]Matching alternating alphanumeric characters with regex

I want to match the following alphanumeric combinations using regex; 我想使用正则表达式匹配以下字母数字组合; ao1 a12 01p p1p 1ap 1p1 . ao1 a12 01p p1p 1ap 1p1

With the following regex I can match all but p1p and 1p1 : 使用以下正则表达式,我可以匹配除p1p and 1p1所有p1p and 1p1

[az][0-9]{1,2}|[0-9]{1,2}[az]|[az][0-9][az]|[az]{1,2}[0-9]|[0-9][az][0-9]

How do I match the alternating number/letter/number and letter/number/letter correctly using regular expressions? 如何使用正则表达式正确匹配交替的number/letter/numberletter/number/letter It needs to match precisely 3 characters, they occur within sentences. 它需要精确匹配3个字符,它们出现在句子中。

You may use 您可以使用

(?<!\S)(?=[a-z]{0,2}\d)(?=\d{0,2}[a-z])[a-z\d]{3}(?!\S)

See the regex demo 正则表达式演示

Details 细节

  • (?<!\\S) - a whitespace or start of string should be immediately to the left of the current location (?<!\\S) -空格或字符串开头应位于当前位置的左侧
  • (?=[az]{0,2}\\d) - there must be a digit after 0 to 2 letters immediately to the right of the current location (?=[az]{0,2}\\d) -当前位置右侧紧靠0到2个字母后必须有一个数字
  • (?=\\d{0,2}[az]) - there must be a letter after 0 to 2 digits immediately to the right of the current location (?=\\d{0,2}[az]) -当前位置右侧的0到2位数字后必须有一个字母
  • [az\\d]{3} - three letters or digits are matched [az\\d]{3} -匹配三个字母或数字
  • (?!\\S) - a whitespace or end of string should be immediately to the right of the current location. (?!\\S) -空格或字符串结尾应在当前位置的右边。

So if you need number/letter/number and letter/number/letter the below should work. 因此,如果您需要数字/字母/数字和字母/数字/字母,则下面的方法应该有效。 But your input ao1 doesn't match this criteria. 但是您输入的ao1不符合此条件。

\d[a-z]\d|[a-z]\d[a-z]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM