Zak Henry
Zak Henry

Reputation: 2185

regex to find number of specific length, but with any character except a number before or after it

I'm trying to work out a regex pattern to search a string for a 12 digit number. The number could have any number of other characters (but not numbers) in front or behind the one I am looking for.

So far I have /([0-9]{12})/ which finds 12 digit numbers correctly, however it also will match on a 13 digit number in the string.

the pattern should match 123456789012 on the following strings

it should match nothing on these strings:

Upvotes: 2

Views: 1780

Answers (2)

Flambino
Flambino

Reputation: 18793

/\D(\d{12})\D/ (in which case, the number will be capture index 1)

Edit: Whoops, that one doesn't work, if the number is the entire string. Use the one below instead

Or, with negative look-behind and look-ahead: /(?<!\d)\d{12}(?!\d)/ (where the number will be capture index 0)


if( preg_match("/(?<!\d)\d{12}(?!\d)/", $string, $matches) ) {
    $number = $matches[0];
    # ....
}

where $string is the text you're testing

Upvotes: 2

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68172

What you want are look-arounds. Something like:

/(?<![0-9])[0-9]{12}(?![0-9])/

A lookahead or lookbehind matches if the pattern is preceded or followed by another pattern, without consuming that pattern. So this pattern will match 12 digits only if they are not preceded or followed by more digits, without consuming the characters before and after the numbers.

Upvotes: 2

Related Questions