How can I match a number with an optional sign and decimal part?
Quick answer
For a deliberately limited ASCII-style format, use ^[+-]?[0-9]+(?:\.[0-9]+)?$ in Python’s re module. It allows one optional plus or minus sign, requires at least one digit, and allows an optional dot followed by at least one digit. It does not allow a leading-dot fraction such as .5 or locale-specific decimal separators, so treat it as a text-shape check, not a universal numeric validator. [S1]
The question, the details, the next step.
A practical checklist
Decide whether at least one digit must appear before a decimal point.
Decide whether a decimal point must have digits after it.
Choose which sign characters and decimal separator the input format allows.
Use
^[+-]?[0-9]+(?:\.[0-9]+)?$for the stated dot-decimal format in Pythonre.Test representative accepted and rejected strings, including boundary cases.
Keep text-shape matching separate from parsing or locale-specific numeric rules.
A few more useful answers
Why does the pattern use `[0-9]` instead of `\d`?
This pattern explicitly describes the ASCII-style digit range [0-9] in the stated format. If your input requirements differ, define the desired digit set rather than assuming this pattern covers every numeric convention. [S1]
How can I allow `.5` as well as `0.5`?
That is a different format from the one shown: the pattern here requires digits before the decimal point. Specify the allowed forms first, then adjust and test the pattern to match those requirements.
Does a match prove the input is a valid number everywhere?
No. It only matches the chosen text shape. The documented pattern excludes leading-dot fractions and locale-specific decimal separators, and does not establish broader numeric conventions. [S1]
Sources
References used for this guide.
- [S1] Python 3 regular-expression operations: character classes and quantifiers docs.python.org · Checked
- [S2] MDN: JavaScript regular-expression quantifiers developer.mozilla.org · Checked
