Sunday, April 22, 2018

How to get the Integer or Numeric part of String in Java ?

How to get the Integer or Numeric part of String in Java ?

Solution :

String str = "| ABC CAR | VIX | 2017 | ABS";

System.out.println(str.replaceAll("[^0-9]", ""));

Output-
2017

Here we have replaced all the characters or whitespaces with blank - ("") .

Note :-

1. Replaceall()

Description
This method replaces each substring of this string that matches the given regular expression with the given replacement.
Signature:
public String replaceAll(String regex, String replacement) 
Reference : https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

2. Regular Expression - Character Classes

[^0-9] - This means any character except 0 to 9 will be replaced (Negation).

Reference : https://docs.oracle.com/javase/tutorial/essential/regex/char_classes.html

2 comments: