Regex patterns/Text & extraction

Leading zeros

A lookahead keeps the last digit safe, so 000 becomes 0 rather than nothing.

/^0+(?=\d)/gm
Open it in Rex

The problem

Strip the padding zeros from a number without deleting the number itself.

How it reads

start0repeatahead: must be\d

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^0+(?=\d)In order:
  2. ^The start of the text (or of a line with the m flag)
  3. 0+The character "0", one or more times, as many as possible
  4. (?=\d)Ahead of here there must be:
  5. \dA digit

Matches

  • 007
  • 0042
  • 000

Does not match

  • 0
  • 42
  • x007

Where it bites

  • Without the lookahead, ^0+ eats all of "000" and leaves an empty string. The lookahead requires a digit to survive.
  • It only fires at the start of a line, which is why the m flag is set — inside a longer string you would need \b instead.
  • Numbers are easier converted than trimmed: Number("007") is 7 with no regex at all.

More text & extraction patterns