Skip to content
shellhacks.dev
Regular Expressions

Match an optional sign and decimal number

Match an optional sign and a decimal number with a fraction group, and anchor it. Unanchored, the pattern matches pieces of 1.2.3 and misses .5 completely.

1 min read
Summarize in AI

You want to accept numbers such as -12 and 3.14 and reject everything else.

Python
import re

pattern = re.compile(r"-?[0-9]+(\.[0-9]+)?")
for s in ["42", "-12", "3.14", "-0.5", ".5", "5.", "1.2.3", "+7", "1e3"]:
    print(f"{s!r:8} fullmatch={bool(pattern.fullmatch(s))}  search={pattern.search(s).group() if pattern.search(s) else None}")
Text
'42'     fullmatch=True  search=42
'-12'    fullmatch=True  search=-12
'3.14'   fullmatch=True  search=3.14
'-0.5'   fullmatch=True  search=-0.5
'.5'     fullmatch=False  search=5
'5.'     fullmatch=False  search=5
'1.2.3'  fullmatch=False  search=1.2
'+7'     fullmatch=False  search=7
'1e3'    fullmatch=False  search=1

The optional group at the end allows a fractional part only when digits follow the dot, so 5. is refused. fullmatch ties the pattern to both ends of the string, as the re module documents, and the search column shows what an unanchored match finds: 1.2.3 yields 1.2, and .5 yields 5, which is wrong in both cases.

This pattern has no leading plus sign and no exponent, so +7 and 1e3 are rejected. Add [+-]? at the front and an optional exponent group at the end if you need them, and allow a leading dot with a second alternative. In grep, use -E and anchor with ^ and $. A regular expression checks the shape, not the range.

Taggedregex
Share

More snippets

Regular Expressions

Match a quoted string

Match a quoted string with a negated character class. An escaped quote inside the text ends the match early, and a PCRE alternation that pairs backslashes handles it.

1 min read
Regular Expressions

Match a semantic version

Match a semantic version with the pattern from semver.org, which runs in grep -E. It rejects leading zeros, a bare 1.2 and a v prefix, and takes pre-release tags.

1 min read
Regular Expressions

Match a UUID

Match a version 4 UUID with 8-4-4-4-12 hex groups, a 4 at the start of the third group and 8, 9, a or b at the start of the fourth. Add -i for uppercase.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.