There are several ways to extract only numbers (int) from a string.
- Add numbers using regular expressions
- Add numbers with for statement
- Add Numbers Using Stream
The easiest way is to use Regex. Let`s look at the methods listed above with examples.
Extract Integer with regular expression
The following code extracts only Integers by regular expression.
Pass the regular expression and the string to be converted as arguments to replaceAll()
.
String str = "aaa1234, ^&*2233pp";
String intStr = str.replaceAll("[^0-9]", "");
System.out.println(intStr);
// output: 12342233
"[^0-9]"
means a non-numeric string from 0 to 9.
So, it means change non-numeric characters to spaces (""
).
The following code also outputs the same result as above.
"^\\d"
is an abbreviation of "[^0-9]"
and has the same meaning.
String str = "aaa1234, ^&*2233pp";
String intStr = str.replaceAll("[^\\d]", "");
System.out.println(intStr);
// output: 12342233
We recommend that you use this method because it has the shortest code.
If you want to know more about regular expressions, refer to Java - Regular Expression (regex) Example.
Extracting numbers with the for statement
The following code extracts only Integers with the for statement.
String str = "aaa1234, ^&*2233pp";
String intStr = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (48 <= ch && ch <= 57) {
intStr += ch;
}
}
System.out.println(intStr);
// output: 12342233
48 means 0 in ASCII, 57 means 9 in ASCII. That is, this code extracts only numbers between 0 and 9 from a string.
Extract numbers with Stream
The following code is for extracting a number from a Stream. The for statement and algorithm are the same. Instead of using for, it was processed using Stream.
String str = "aaa1234, ^&*2233pp";
IntStream stream = str.chars();
String intStr = stream.filter((ch)-> (48 <= ch && ch <= 57))
.mapToObj(ch -> (char)ch)
.map(Object::toString)
.collect(Collectors.joining());
System.out.println(intStr);
// output: 12342233
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)