kernelpanic kernelpanic - 1 year ago 47
Perl Question

Matching a number a max number of times

I have the following regex in Perl that works for matching strings with 6 or fewer digits in them. However, this also matches strings with more than 6 digits.

$string =~ /[0-9]{1,6}/


  1. T12345#1

  2. 0897

  3. 112355501234

I'd like the regex to match the first 2 but not the last case.

Answer Source

Use a negated look ahead to see if a digit follows, and negated look behind so you don't just match the last six digits:

$string =~ /(?<!\d)\d{1,6}(?!\d)/