Search code examples
regexsubstringleading-zero

Regex remove leading zeros if string is number


How can I remove leading zeros if the input is a number and otherwise not?

Specific scenario: I am only interested in the last 10 characters of the input. If this substring is consisting only of numbers, I want to remove the leading zeros. Otherwise, so if there is a word character or a special character, I need this whole substring.

Example 1

input: aaaa000002d111

expected: 000002d111 (because of the 'd' in the substring)


Example 2

input: aaaa0000011111

expected: 11111

I managed to remove the leading zeros with 0*(.{0,10})$ but how do I proceed in case any non-digit is included?

If possible, it would be perfect, if this expected substring is in group 1 of the match.


Solution

  • .{4}(?:0*([1-9]{1,10}|\w{10}))$

    skip the first 4 chars then search for either 10 digits (excluding any leading zeros) or the last 10 characters if not all digits. Both return in Group 1

    see demo here

    UPDATE

    as per comments, changed the regex to allow 0 within the digits (after the first non-zero digit)

    .{4}(?:0*([1-9]\d{1,9}|\w{10}))$

    see updated demo here