- Java Regular Expression to Check If String contains at least One Digit
- Regular Expression to Find if String contains Number or Not
- Java — check if string only contains numbers
- 1. Using regex
- 2. Using Character.isDigit()
- Extract Numbers From String Using Java Regular Expressions
- Extract All Numbers from a String
- Extract nth Digit from a String
- Extract Number from a Tag Attribute
- Extract a String Containing digits and Characters
- Extract Key-Value Pairs With Regular Expressions
- What’s the Java regular expression for an only integer numbers string?
Java Regular Expression to Check If String contains at least One Digit
This week’s task is to write a regular expression in Java to check if a String contains any digit or not. For example, passing «abcd» to pattern should false , while passing «abcd1» to return true , because it contains at least one digit. Similarly passing «1234» should return true because it contains more than one digit. Though java.lang.String class provides a couple of methods with inbuilt support of regular expression like split method, replaceAll(), and matches method, which can be used for this purpose, but they have a drawback. They create a new regular expression pattern object, every time you call. Since most of the time we can just reuse the pattern, we don’t need to spend time on creating and compiling patterns, which is expensive compared to testing a String against the pattern.
For reusable patterns, you can take the help of java.util.regex package, it provides two class Pattern and Matcher to create pattern and check String against that pattern.
In order to complete this, we first need to create a regular expression pattern object, we can do that by passing regular expression String «(.)*(\\d)(.)*» to Pattern.compile() method, this returns a compiled version of regular expression String. By using this pattern you can get Matcher object to see if the input string passes this regular expression pattern or not.
We will learn more about our regular expression String in the next section when we will see our code example to check if String contains a number or not.
Regular Expression to Find if String contains Number or Not
The following code sample is our complete Java program to check if String contains any number or not. You can copy this code into your favorite IDE like Eclipse, Netbeans, or IntelliJ IDEA. Just create a Java source file with the name of our public class RegularExpressionDemo and run it from IDE itself.
Alternatively, you can run the Java program from the command line by first compiling a Java source file using the javac compiler and then running it using the java command.
Now let’s understand the core of the program, the regular expression itself. We are using «(.)*(\\d)(.)*» , where dot and start are meta characters used for any character and any number of timer. \d is a character class for matching digits, and since backward slash needs to escaped in Java, we have put another backslash e.g. \\d ..
So if you read this regular expression, it days any character any number of time, followed by any digit then again any character any number of time. This means this will match any String which contains any numeric digit e.g. from 0 — 9.
import java.util.Scanner ;
Java — check if string only contains numbers
Lia-Perez
In this article, we would like to show you how to check if the string only contains numbers in Java.
1. Using regex
In this example, we use a regular expression (regex) with Pattern.matcher() to check if the strings contain only numbers.
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example < public static void main(String[] args) < String numbers = "1234"; String text = "ABC"; String regex = "^1+$"; // regex to check if string contains only digits Pattern pattern = Pattern.compile(regex); // compiles the regex // find match between given string and pattern Matcher matcherNumbers = pattern.matcher(numbers); Matcher matcherText = pattern.matcher(text); // return true if the string matched the regex Boolean numbersMatches = matcherNumbers.matches(); Boolean textMatches = matcherText.matches(); System.out.println(numbersMatches); // true System.out.println(textMatches); // false >>
2. Using Character.isDigit()
In this example, we create a function that loops through the string and checks if each character is a digit with Character.isDigit(char ch) method.
public class Example < public static void main(String[] args) < String numbers = "1234"; String text = "ABC"; System.out.println(onlyNumbers(numbers)); // true System.out.println(onlyNumbers(text)); // false >public static boolean onlyNumbers(String string) < if (string == null || string.isEmpty()) < return false; >for (int i = 0; i < string.length(); ++i) < if (!Character.isDigit(string.charAt(i))) < return false; >> return true; > >
Extract Numbers From String Using Java Regular Expressions
The following are examples which show how to extract numbers from a string using regular expressions in Java.
Being able to parse strings and extract information from it is a key skill that every tester should have. This is particularly useful when testing APIs and you need to parse a JSON or XML response.
The following Java Regular Expression examples focus on extracting numbers or digits from a String.
Extract All Numbers from a String
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < public static void main(String[]args) < Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher("string1234more567string890"); while(m.find()) < System.out.println(m.group()); >> >
Extract nth Digit from a String
If you want to extract only certain numbers from a string you can provide an index to the group() function.
For example, if we wanted to only extract the second set of digits from the string string1234more567string890 , i.e. 567 then we can use:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < private static final Pattern p = Pattern.compile("[^\\d]*[\\d]+[^\\d]+([\\d]+)"); public static void main(String[] args) < // create matcher for pattern p and given string Matcher m = p.matcher("string1234more567string890"); // if an occurrence if a pattern was found in a given string. if (m.find()) < System.out.println(m.group(1)); // second matched digits >> >
Explanation of the Pattern [^\d]*[\d]+[^\d]+([\d]+)
- ignore any non-digit
- ignore any digit (first number)
- again ignore any non-digit
- capture the second number
Extract Number from a Tag Attribute
When dealing with XML or HTML tags, sometimes there is a need to extract a value from an attribute. For example, consider the following tag
To extract number 9999 we can use the following code:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < public static void main(String[]args) < Pattern pattern = Pattern.compile("numFound=\"(6+)\""); Matcher matcher = pattern.matcher(""); if (matcher.find()) < System.out.println(matcher.group(1)); >> >
Extract a String Containing digits and Characters
You can use Java regular expressions to extract a part of a String which contains digits and characters. Suppose we have this string Sample_data = YOUR SET ADDRESS IS 6B1BC0 TEXT and we want to extract 6B1BC0 which is 6 characters long, we can use:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < public static void main (String[] args) < Pattern p = Pattern.compile("YOUR SET ADDRESS IS\\s+([A-Z0-9])"); Matcher n = p.matcher("YOUR SET ADDRESS IS 6B1BC0 TEXT"); if (n.find()) < System.out.println(n.group(1)); // Prints 123456 >> >
Extract Key-Value Pairs With Regular Expressions
Let’s suppose we have a string of this format bookname=testing&bookid=123456&bookprice=123.45 and we want to extract the key-value pair bookid=123456 we would use:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples < public static void main(String[] args) < String s = "bookname=cooking&bookid=123456&bookprice=123.45"; Pattern p = Pattern.compile("(?<=bookid=)\\d+"); Matcher m = p.matcher(s); if (m.find()) < System.out.println(m.group()); >> >
What’s the Java regular expression for an only integer numbers string?
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:
As others have already said, java doesn’t use delimiters. The string you’re trying to match doesn’t need the trailing slashes, so instead of /^\\d+$/ your string should’ve been ^\\d+$ .
Now I know this is an old question, but most of the people here forgot something very important. The correct regex for integers:
^ String start metacharacter (Not required if using matches() - read below) -? Matches the minus character (Optional) \d+ Matches 1 or more digit characters $ String end metacharacter (Not required if using matches() - read below)
Of course that in Java you’d need a double backslash instead of the regular backslash, so the Java string that matches the above regex is ^-?\\d+$
NOTE: The ^$ (string start/end) characters aren’t needed if you’re using .matches() :
Welcome to Java’s misnamed .matches() method. It tries and matches ALL the input. Unfortunately, other languages have followed suit 🙁
— Taken from this answer
The regex would still work with the ^$ anyways. Even though it’s optional I’d still include it for regex readability, as in every other case when you don’t match the entire string by default (which is most of the time if you’re not using .matches() ) you’d use those characters
The \D is everything that is not a digit. The \D (Non digits) negates \d (digits).
Integer regex on regex101
Notice that this is just for integers. The regex for doubles:
^ String start metacharacter (Not required if using matches()) -? Matches the minus character. The ? sign makes the minus character optional. \d+ Matches 1 or more digit characters ( Start capturing group \.\d+ A literal dot followed by one or more digits )? End capturing group. The ? sign makes the whole group optional. $ String end metacharacter (Not required if using matches())
Of course that in Java instead of \d and \. you’d have double backslashes as the above example does.
Doubles regex on regex101
Java doesn’t use slashes to delimit regular expressions.
FYI the String.matches() method must match the whole input to return true .
Even in languages like perl, the slashes are not part of the regex; they are delimiters — part if the application code, nothing to do with the regex