正则表达式匹配范围0-255,没有^和$

时间:2017-07-12 03:14:45

标签: regex regular-language

有没有办法在没有^$的情况下匹配一系列数字(0-255)?

匹配数字

  • 1
  • 12
  • 123

不匹配的数字

  • 1234
  • 555

2 个答案:

答案 0 :(得分:1)

您可以使用lookahead和lookbehind来匹配 1-3位数。

(?<!\d)(?:[1-9]?\d|1\d\d|2(?:[0-4]\d|5[0-5]))(?!\d)

Regex101 demo

答案 1 :(得分:1)

Not using anchor characters, BrightOne was wise to integrate lookarounds for numeric characters. However, the pattern isn't fully refined. To optimize the pattern for speed and maintain accuracy:

  1. Use quantifiers on consecutive duplicate characters.
  2. Organize the alternatives not in sequential order but with quickest mis-matches first.
  3. Avoid non-essential capture (or non-capture) groups. (despite seeming logical to condense the "two hundreds" portion of the pattern)

This is my suggested pattern: (Demo)

/(?<!\d)(?:1\d{2}|2[0-4]\d|[1-9]?\d|25[0-5])(?!\d)/  #3526 steps

(Brightone's pattern resolves in 5155 steps)
(treesongs' second pattern resolves in 5184 steps) *at time of posting, the first pattern was inaccurate)