John Doe
John Doe

Reputation: 10203

Find number with optional leading zeros but not starting with another digit

I need to find a specific number with optional leading zeros but not starting or ending with another digit.

Sample line:

"123456, 123456A, A123456, A123456A, 0123456, 9123456, 1234567, ABCD0000123456 or /123456"

Regex I'm currently using:

"0*?[^1-9]123456(?!\d)"

Current matches:

 123456
A123456
A123456
0123456
0000123456
/123456

How to avoid the 123456,A123456 and /123456 matches (want to match only 123456 from these). A or ABCD can be any other character except digits!

Desired matches:

123456
123456
123456
123456
0123456
0000123456
123456

What's the best regex for this?
Thanks in advance

Upvotes: 0

Views: 290

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627100

You need to remove [^1-9] and use (?<!\d) negative lookbehind before 0* pattern:

(?<!\d)0*123456(?!\d)

See the regex demo and the regex graph:

enter image description here

Details

  • (?<!\d) - no digit immediately to the left is allowed
  • 0* - zero or more 0 digits
  • 123456 - a specific digit string
  • (?!\d) - no digit immediately to the right of the current location is allowed.

Upvotes: 2

Related Questions