-1

Is there a way to match a range of numbers(0-255) without the ^ and $?

Matched numbers

  • 1
  • 12
  • 123

Not matched numbers

  • 1234
  • 555
chenzhiwei
  • 441
  • 6
  • 14
  • What do you mean under `without the ^ and $`? – zwer Jul 12 '17 at 03:28
  • Unless your engine anchor the complete expression, you will need some kind of delimiter that prevents parts of invalid numbers to be matched. There are many workarounds, but why not just use `^` and `$`? – Bergi Jul 12 '17 at 03:53
  • @zhiwei this question may qualify for re-opening if you edit your question to ask for patterns that permit lookarounds. Otherwise, the duplicate link is appropriate. – mickmackusa Jul 12 '17 at 09:03

2 Answers2

1

You can use lookahead and lookbehind to match only 1-3 digits.

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

Regex101 demo

Oleksii Filonenko
  • 1,551
  • 1
  • 17
  • 27
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)

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • That's a well-crafted regex. Nice work @mickmackusa! This should be an accepted answer. *"Mastering Regular Expressions" didn't help me at all* – Oleksii Filonenko Jul 12 '17 at 09:29
  • @BrightOne See the guy who closed this question? That is who I learn the most from. I recommend that if you want to learn some wicket-awesome techniques just follow his posts on SO. There are certainly other highly skilled posters who are just as worthy of watching -- you will know them when you see them. Hang out on SO, you will learn HEAPS! – mickmackusa Jul 12 '17 at 09:51
  • Thanks, I'll check this out :) – Oleksii Filonenko Jul 12 '17 at 09:52