正则表达式的较短方式

shorter way of a regex

这必须只匹配这些数字:110, 220, 330, 440, 550, 660, 770, 880, 990(不包括 000)。这个正则表达式 (pcre) 有更短的方法吗?

/^(1{2}|2{2}|3{2}|4{2}|5{2}|6{2}|7{2}|8{2}|9{2})0$/

您可以使用:

/\b([1-9])\g{1}0\b/

RegEx Demo

正则表达式分解:

\b      # word boundary
[1-9]   # match digit 1-9 and group them as captured group #1
\g{1}   # back-reference to group #1
0       # match 0
\b      # word boundary

这是一个应该可以工作的较短的正则表达式:

/^([1-9])[0]$/

它使用对第一个匹配字符的反向引用来匹配第二个。这确保了 112233 等模式。

这里是对 regex101 表达式中使用的字符的解释:

  • ^ assert position at start of a line
  • 1st Capturing group ([1-9])
    • [1-9] match a single character in the range between 1 and 9
  • </code> matches the same text as most recently matched by the 1st capturing group</li> <li><code>[0] matches the character 0 literally
  • $ assert position at end of a line

你可以在这里测试: https://regex101.com/r/oV6rE7/1