Extract numbers in string java

Extract Numbers from String – Java

Java code to extract digits or numbers from a string with logic and explanation. We’ll use 2 methods: (1) using regex expression with replaceAll method of String object, and (2) using loop and ascii values of characters.

Extract Numbers from String using regex

Use the regular expression [^0-9] to find non-integer characters in the string and replace them with an empty value using the method replaceAll.

Output: 123421

EXPLANATION:

The String method “String replaceAll(String regex, String replacement)” finds the characters or patterns in the given string using the regex expression provided by you and replaces them with the option that you provide.

In the given program, the regex [^0-9] matches any single character that is not a number, and the method replaces those characters with an empty value specified by “”.

The regular expression replaceAll(“\\D+”, “”); will also work to extract numbers or digits.

Extract Numbers from String using loop and ascii value

Go over all the characters in the string using a loop, get the ascii code for each character. Check if the ascii code is between 48 and 57 (ascii for 0 is 48, for 1 is 49 ……and 9 is 57). If ascii comes between the range 48 and 47, then construct the numbers. You can store into a string value e.g. numString in the given code below. Finally convert that number string to an integer value. That’s it.

public class Sample < public static void main(String[] args) < String str = "XXXX1234G21#"; String numString = ""; for (int i = 0; i < str.length(); i++) < int ascii = str.charAt(i); // ascii value of 0 is 48 and of 9 is 57 if (ascii >= 48 && ascii > // Convert number in string form to //an integer value int numbers = Integer.parseInt(numString); System.out.println(numbers); > > 

Output:123421

EXPLANATION:

Using a for loop the given string is iterated up to the string length. The charAt(i) method returns character at given index but if you store into an integer variable it will be the ascii value of that character.

Check if the ascii value is in the range 48 and 57, then construct the integers in form of a string. This would be the string of all integers separated.

Convert the integer string into a number. That will result the output.

Читайте также:  Modulenotfounderror no module named setuptools python

Uses of Extracting Numbers from String:

Here is a scenario in real-time where you may need to extract numbers from strings.

Suppose you have a text file containing millions of user’s names and their phone numbers. And,

you want to send SMS to all the users via an application. The application can read the content of the file and extract the phone number and send the SMS to all.

Источник

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.

Источник

Find All Numbers in a String in Java

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

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:

announcement - icon

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.

Читайте также:  For loop java method

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:

announcement - icon

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.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

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.

Читайте также:  Php fpm exporter prometheus

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.

announcement - icon

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:

Источник

Оцените статью