Only Numbers In Regex (Regular Expression)

Numbers can be matched or searched by using regex patterns. The regex can be expressed as there is no character or letter and only contains numbers. This regex can be used only for numbers in different platforms or programming languages like C#, Java, JavaScript, etc. Regex is a generic expression language where different text patterns can be expressed in different ways.

Match Numbers One By One

The \d is used to express single number in regex. The number can be any number which is a single number. The \d can be used to match single number.

\d

Alternatively the [0-9] can be used to match single number in a regular expression. The [0-9] means between 0 and 9 a single number can match. The letters can not match in this case.

[0-9]

Match Number Group

The number group can be also matched with a regex. The numbers side by side match as a group in this case. The number expressions of the regex are used multiple times by using the * or + operators. The + operator means single or more characters and if there are multiple characters they are matched as a group.

\d+
[0-9]+

Match Lines Starting with Numbers

The numbers can be located at the start of the line. These numbers can be matched by using the ^ sign which is used to express the start of the line.

^\d+
^\[0-9]+

Match Lines Ending with Numbers

The numbers at the end of the line can be matched by using $ in the regex. The $ sign is used to express end of the line. The following regex can be used to match numbers at the end of the line.

\d+$
\[0-9]+$

Match Only Number Lines

In some cases we may need to match lines those only consist of numbers. These lines do not contains non-numeric characters. The ^ and $ are used to set start and end of line which consist of only numbers.

^\d+$
^[0-9]+$

Leave a Comment