- 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
- How to extract digits from a string in Java
- You might also like.
- Java — check if string only contains numbers
- 1. Using regex
- 2. Using Character.isDigit()
- Find All Numbers in a String in Java
- 1. Overview
- 2. Counting Numeric Digits
- 2.1. Using Regular Expressions
- 2.2. Using the Google Guava CharMatcher
- 3. Finding Numbers
- 3.1. Finding Integers
- 3.2. Finding Decimal Numbers
- 4. Converting the Strings Found into Numeric Values
- 5. Finding Other Types of Numbers
- 5.1. Scientific Notation
- 5.2. Hexadecimal
- 6. Conclusion
Extract Numbers From String Using Java Regular Expressions
Last updated: 11 February 2020 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=\"(8+)\""); 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()); >> >
How to extract digits from a string in Java
There are various ways to extract digits from a string in Java. The easiest and straightforward solution is to use the regular expression along with the String.replaceAll() method.
The following example shows how you can use the replaceAll() method to extract all digits from a string in Java:
// string contains numbers String str = "The price of the book is $49"; // extract digits only from strings String numberOnly = str.replaceAll("[^0-9]", ""); // print the digitts System.out.println(numberOnly);
The above example will output 49 on the console. Notice the regular expression [^0-9] we used above. It indicates that replace everything except digits from 0 to 9 with an empty string. This is precisely what we need.
Alternatively, You can also use \\D+ as a regular expression because it produces the same result:
String numberOnly = str.replaceAll("\\D+", "");
The replaceAll() method compiles the regular expression every time it executes. It works for simple use cases but is not an optimal approach. You should rather use the Pattern class to compile the given regular expression into a pattern as shown below:
Pattern pattern = Pattern.compile("[^0-9]"); String numberOnly = pattern.matcher(str).replaceAll("");
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
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 = "^3+$"; // 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; > >
Find All Numbers in a String in Java
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
Sometimes we need to find numeric digits or full numbers in strings. We can do this with both regular expressions or certain library functions.
In this article, we’ll use regular expressions to find and extract numbers in strings. We’ll also cover some ways to count digits.
2. Counting Numeric Digits
Let’s start by counting the digits found within a string.
2.1. Using Regular Expressions
In regular expressions, “\d“ matches “any single digit”. Let’s use this expression to count digits in a string:
int countDigits(String stringToSearch) < Pattern digitRegex = Pattern.compile("\\d"); Matcher countEmailMatcher = digitRegex.matcher(stringToSearch); int count = 0; while (countEmailMatcher.find()) < count++; >return count; >
Once we have defined a Matcher for the regex, we can use it in a loop to find and count all the matches. Let’s test it:
int count = countDigits("64x6xxxxx453xxxxx9xx038x68xxxxxx95786xxx7986"); assertThat(count, equalTo(21));
2.2. Using the Google Guava CharMatcher
To use Guava, we first need to add the Maven dependency:
com.google.guava guava 31.0.1-jre
Guava provides the CharMatcher.inRange method for counting digits:
int count = CharMatcher.inRange('0', '9') .countIn("64x6xxxxx453xxxxx9xx038x68xxxxxx95786xxx7986"); assertThat(count, equalTo(21));
3. Finding Numbers
Counting numbers requires patterns that capture all the digits of a valid numeric expression.
3.1. Finding Integers
To construct an expression to recognize integers, we must consider that they can be positive or negative and consist of a sequence of one or more digits. We also note that negative integers are preceded by a minus sign.
Thus, we can find integers by extending our regex to “-?\d+“. This pattern means “an optional minus sign, followed by one or more digits”.
Let’s create an example method that uses this regex to find integers in a string:
List findIntegers(String stringToSearch) < Pattern integerPattern = Pattern.compile("-?\\d+"); Matcher matcher = integerPattern.matcher(stringToSearch); ListintegerList = new ArrayList<>(); while (matcher.find()) < integerList.add(matcher.group()); >return integerList; >
Once we have created a Matcher on the regex, we use it in a loop to find all the integers in a string. We call group on each match to get all the integers.
List integersFound = findIntegers("646xxxx4-53xxx34xxxxxxxxx-35x45x9xx3868xxxxxx-95786xxx79-86"); assertThat(integersFound) .containsExactly("646", "4", "-53", "34", "-35", "45", "9", "3868", "-95786", "79", "-86");
3.2. Finding Decimal Numbers
To create a regex that finds decimal numbers, we need to consider the pattern of characters used when writing them.
If a decimal number is negative, it starts with a minus sign. This is followed by one or more digits and an optional fractional part. This fractional part starts with a decimal point, with another sequence of one or more digits after that.
We can define this using the regular expression “-?\d+(\.\d+)?“:
List findDecimalNums(String stringToSearch) < Pattern decimalNumPattern = Pattern.compile("-?\\d+(\\.\\d+)?"); Matcher matcher = decimalNumPattern.matcher(stringToSearch); ListdecimalNumList = new ArrayList<>(); while (matcher.find()) < decimalNumList.add(matcher.group()); >return decimalNumList; >
Now we’ll test findDecimalNums:
List decimalNumsFound = findDecimalNums("x7854.455xxxxxxxxxxxx-3x-553.00x53xxxxxxxxxxxxx3456xxxxxxxx3567.4xxxxx"); assertThat(decimalNumsFound) .containsExactly("7854.455", "-3", "-553.00", "53", "3456", "3567.4");
4. Converting the Strings Found into Numeric Values
We may also wish to convert the found numbers into their Java types.
Let’s convert our integer numbers into Long using Stream mapping:
LongStream integerValuesFound = findIntegers("x7854x455xxxxxxxxxxxx-3xxxxxx34x56") .stream() .mapToLong(Long::valueOf); assertThat(integerValuesFound) .containsExactly(7854L, 455L, -3L, 34L, 56L);
Next, we’ll convert decimal numbers to Double in the same way:
DoubleStream decimalNumValuesFound = findDecimalNums("x7854.455xxxxxxxxxxxx-3xxxxxx34.56") .stream() .mapToDouble(Double::valueOf); assertThat(decimalNumValuesFound) .containsExactly(7854.455, -3.0, 34.56);
5. Finding Other Types of Numbers
Numbers can be expressed in other formats, which we can detect by adjusting our regular expressions.
5.1. Scientific Notation
Let’s find some numbers formatted using scientific notation:
String strToSearch = "xx1.25E-3xxx2e109xxx-70.96E+105xxxx-8.7312E-102xx919.3822e+31xxx"; Matcher matcher = Pattern.compile("-?\\d+(\\.\\d+)?[eE][+-]?\\d+") .matcher(strToSearch); // loop over the matcher assertThat(sciNotationNums) .containsExactly("1.25E-3", "2e109", "-70.96E+105", "-8.7312E-102", "919.3822e+31");
5.2. Hexadecimal
Now we’ll find hexadecimal numbers in a string:
String strToSearch = "xaF851Bxxx-3f6Cxx-2Ad9eExx70ae19xxx"; Matcher matcher = Pattern.compile("-?[0-9a-fA-F]+") .matcher(strToSearch); // loop over the matcher assertThat(hexNums) .containsExactly("aF851B", "-3f6C", "-2Ad9eE", "70ae19");
6. Conclusion
In this article, we first discussed how to count digits in a string using regular expressions and the CharMatcher class from Google Guava.
Then, we explored using regular expressions to find integers and decimal numbers.
Finally, we covered finding numbers in other formats such as scientific notation and hexadecimal.
As always, the source code for this tutorial can be found over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: