PHP Regex match increment ids with optional spaces

Viewed 40

Trying to find increments in strings like intended purpose (banking) ect.

I try to create a regex that matches 123456 ... and 123 456 ....

I receive the intended purpose lines imploded without empty space. So i will get the increment like FooBar 123456 Baz FooBar 123456Baz or FooBar123456Baz.

The increments start with 15 or 16. Examples: 150000000001 160000000001.

What i got: (^\s*|[^0-9])((15|16)(?:\d\s?){10})([^0-9]|\s*$)

Pattern break down:
#

// Begin of string (perhaps empty spaces) OR no digit.
(^\s*|[^0-9])

// Prefix "15" or "16" and 10 digits (perhaps empty spaces between).
((15|16)(?:\d\s?){10})
                      
// Not following by digit OR (perhaps empty spaces between) end of string.
([^0-9]|\s*$)
                      
#

First problem i have is that (?:\d\s?) always selects an empty space after. Second problem is that my attempts on the beginning and the end do not really work.

The main part is ((15|16)(?:\d\s?){10}). But this also continues to select after line breaks, which it should not. That is why i try to limit the matches with the "not 0-9 OR end|start of line".

Im testing this at regex101.com

Examples what it should match:

-- no empty space at start of line, and one or more spaces between, and none-number before|after
150000000001 150000000001  150000000001 150000000001 d 150000000001d 150000000001 d150000000001d

-- empty space before and in between
 150 000 000 001
 15 00 00 00 00 01 --not a must tho
150000000001    -- just a string of the increment only
160000000001    -- just a string of the increment only

The new line problem -

-- the new line problem
Foo Bar160000000
001 Baz

selects

160000000
001

which it should not.

How to i proper restrict the beginning and the end?

Thank you for your time.

1 Answers

You can use

/(?<!\d)1[56]\d(?:\h?\d){9}(?!\d)/

The regex matches:

  • (?<!\d) - a left-hand digit boundary, no digit is allowed immediately on the left
  • 1 - a 1 char
  • [56] - a 5 or 6 char
  • \d - any digit
  • (?:\h?\d){9} - nine occurrences of an optional horizontal whitespace and any one digit
  • (?!\d) - a right-hand digit boundary, no digit is allowed immediately on the right.
Related