What's the Java regular expression for an only integer numbers string?

java, regex

Solution

In Java regex, you don't use delimiters `/`:

nuevo_precio.getText().matches("^\\d+$")

Since `String.matches()` (or `Matcher.matcher()`) force the whole string to match against the pattern to return `true`, the `^` and `$` are actually redundant and can be removed without affecting the result. This is a bit different compared to JavaScript, PHP (PCRE) or Perl, where "match" means finding a substring in the target string that matches the pattern.

nuevo_precio.getText().matches("\\d+") // Equivalent solution

It doesn't hurt to leave it there, though, since it signifies the intention and makes the regex more portable.

To limit to exactly 4 digit numbers:

"\\d{4}"

Problem

I'm trying with `if (nuevo_precio.getText().matches("/^\\d+$/"))` but got not good results so far...

Original source

Related problems