Regex For Numbers Only

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ႒ (Myanmar 2) and ߉ (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

Regex for numbers only

Use the beginning and end anchors.

Regex regex = new Regex(@"^\d$");

Use "^\d+$" if you need to match more than one digit.


Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ٠١٢٣٤٥٦٧٨٩. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.


If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.

Regex to allow only numbers and max 2 digits

I would recommend to update regex to allow 0 or 2 digits- /^[0-9]{0,2}$/.

The following values will match: '', '0', '1', ... '10', ... '99'.

keypress event has the following fields:

  • event.target.value - value of input before new key was pressed
  • event.key - string value of the key that was pressed

When event.target.value and event.key are combined together we can estimate new value of the input.

event.preventDefault() call can be used to block keypress event if the resulting value does not match the needed pattern.

document.getElementById('myinput').addEventListener('keypress', event => {
if (!`${event.target.value}${event.key}`.match(/^[0-9]{0,2}$/)) {
// block the input if result does not match
event.preventDefault();
event.stopPropagation();
return false;
}
});
<input id="myinput" type="text" value="" />

Regex to check whether a string contains only numbers

var reg = /^\d+$/;

should do it. The original matches anything that consists of exactly one digit.

How to check if a string contains only digits in Java

Try

String regex = "[0-9]+";

or

String regex = "\\d+";

As per Java regular expressions, the + means "one or more times" and \d means "a digit".

Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d in a java String gives you the actual result: \d

References:

  • Java Regular Expressions

  • Java Character Escape Sequences


Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.

Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:

String regex = "\\d+";

// positive test cases, should all be "true"
System.out.println("1".matches(regex));
System.out.println("12345".matches(regex));
System.out.println("123456789".matches(regex));

// negative test cases, should all be "false"
System.out.println("".matches(regex));
System.out.println("foo".matches(regex));
System.out.println("aa123bb".matches(regex));

Question 1:

Isn't it necessary to add ^ and $ to the regex, so it won't match "aa123bb" ?

No. In java, the matches method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$ (even though it is also correct). Please see the last negative test case.

Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find method instead, described in detail here:

Difference between matches() and find() in Java Regex

Question 2:

Won't this regex also match the empty string, "" ?*

No. A regex \\d* would match the empty string, but \\d+ does not. The star * means zero or more, whereas the plus + means one or more. Please see the first negative test case.

Question 3

Isn't it faster to compile a regex Pattern?

Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches, and so if performance implications are important then a Pattern can be compiled and used like this:

Pattern pattern = Pattern.compile(regex);
System.out.println(pattern.matcher("1").matches());
System.out.println(pattern.matcher("12345").matches());
System.out.println(pattern.matcher("123456789").matches());

REGEX a-z 0-9 but not only numbers

The \D shorthand class means any non-digit symbol. You should remove it from the pattern (so that it becomes "^[A-Za-z0-9_-]{10,30}$") for the matches to return true, as 1 is a digit in 1Regex that accepts only numbers (0-9) and NO characters Regex for numbers only Regex to allow only numbers and max 2 digits Regex to check whether a string contains onle333e.

If you want to place a restriction (the string cannot consist of only digits) use an anchored look-ahead:

^(?![0-9]+$)[A-Za-z0-9_-]{10,30}$

Here is a demo

Or, a shortened version with i modifier making the pattern case-insensitive:

(?i)^(?![0-9]+$)[A-Z0-9_-]{10,30}$

allow only numbers AND may 'contain' slash AND must not start or end with slash

The [^/] matches any char, not just a digit. Besides, to validate a whole string, you need to use anchors, or a method that anchors the match at start and end of the string.

You may use

^(?!\/)[\d\/]*$(?<!\/)

Or

^\d(?:[\/\d]*\d)?$

See the regex demo #1 and regex demo #2.

Regex #1 details

  • ^ - start of string
  • (?!\/) - no / allowed at the start
  • [\d\/]* - 0 or more digits or slashes
  • $- end of string
  • (?<!\/) - fail the match if there is a / at the end.

Regex #2 details

  • ^ - start of string
  • \d - a digit
  • (?:[\/\d]*\d)? - an optional non-capturing group matching 0 or more / or digit chars and then a digit
  • $ - end of string.

Regex expression for numbers and leading zeros just with a dot and decimal

If a negative lookahead is supported, you can exclude matches that start with a zero and have no decimal part.

^(?!0\d*$)\d+(?:\.\d{1,2})?$
  • ^ Start of string
  • (?!0+\d*$) Negative lookahead, assert not a zero followed by optional digits at the right
  • \d+ Match 1+ digits
  • (?:\.\d{1,2})? Match an optional decimal part with 1 or 2 digits
  • $ End of string

Regex demo



Related Topics



Leave a reply



Submit