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.
Number out of string in java
Solution 1: You can use following call to replace all numbers (followed by 0 or more spaces) by an empty string: Solution 2: You can perhaps use something like this: Solution 2: Use the following RegExp (see http://java.sun.com/docs/books/tutorial/essential/regex/): By: Solution 3: Solution 4: You could probably do it along these lines: It’s easily adaptable to multiple number group as well.
Number out of string in java
I have something like «ali123hgj». i want to have 123 in integer. how can i make it in java?
int i = Integer.parseInt("blah123yeah4yeah".replaceAll("\\D", "")); // i == 1234
Note how this will «merge» digits from different parts of the strings together into one number. If you only have one number anyway, then this still works. If you only want the first number, then you can do something like this:
int i = Integer.parseInt("x-42x100x".replaceAll("^\\D*?(-?\\d+).*$", "$1")); // i == -42
The regex is a bit more complicated, but it basically replaces the whole string with the first sequence of digits that it contains (with optional minus sign), before using Integer.parseInt to parse into integer.
Use the following RegExp (see http://java.sun.com/docs/books/tutorial/essential/regex/):
final Pattern pattern = Pattern.compile("\\d+"); // the regex final Matcher matcher = pattern.matcher("ali123hgj"); // your string final ArrayList ints = new ArrayList(); // results while (matcher.find()) < // for each match ints.add(Integer.parseInt(matcher.group())); // convert to int >
This is the Google Guava #CharMatcher Way.
String alphanumeric = "12ABC34def"; String digits = CharMatcher.JAVA_DIGIT.retainFrom(alphanumeric); // 1234 String letters = CharMatcher.JAVA_LETTER.retainFrom(alphanumeric); // ABCdef
If you only care to match ASCII digits, use
String digits = CharMatcher.inRange('0', '9').retainFrom(alphanumeric); // 1234
If you only care to match letters of the Latin alphabet, use
String letters = CharMatcher.inRange('a', 'z') .or(inRange('A', 'Z')).retainFrom(alphanumeric); // ABCdef
You could probably do it along these lines:
Pattern pattern = Pattern.compile("[^0-9]*(2*)[^0-9]*"); Matcher matcher = pattern.matcher("ali123hgj"); boolean matchFound = matcher.find(); if (matchFound)
It’s easily adaptable to multiple number group as well. The code is just for orientation: it hasn’t been tested.
Check if String Contains Numbers in Java, Java has a class, the Java String class, which has a lot of methods to manipulate Java strings in different ways. To find out the presence of a number in a string, we can use some of the built-in methods provided by the Java library. But before we start, as a prerequisite, we must also know about regex or regular …
How to get numbers out of string?
I’m using a Java streamtokenizer to extract the various words and numbers of a String but have run into a problem where numbers which include commas are concerned, e.g. 10,567 is being read as 10.0 and ,567.
I also need to remove all non-numeric characters from numbers where they might occur, e.g. $678.00 should be 678.00 or -87 should be 87.
I believe these can be achieved via the whiteSpace and wordChars methods but does anyone have any idea how to do it?
The basic streamtokenizer code at present is:
BufferedReader br = new BufferedReader(new StringReader(text)); StreamTokenizer st = new StreamTokenizer(br); st.parseNumbers(); st.wordChars(44, 46); // ASCII comma, - , dot. st.wordChars(48, 57); // ASCII 0 - 9. st.wordChars(65, 90); // ASCII upper case A - Z. st.wordChars(97, 122); // ASCII lower case a - z. while (st.nextToken() != StreamTokenizer.TT_EOF) < if (st.ttype == StreamTokenizer.TT_WORD) < System.out.println("String: " + st.sval); >else if (st.ttype == StreamTokenizer.TT_NUMBER) < System.out.println("Number: " + st.nval); >> br.close();
Or could someone suggest a REGEXP to achieve this? I’m not sure if REGEXP is useful here given that any parding would take place after the tokens are read from the string.
StreamTokenizer is outdated, is is better to use Scanner, this is sample code for your problem:
String s = "$23.24 word -123"; Scanner fi = new Scanner(s); //anything other than alphanumberic characters, //comma, dot or negative sign is skipped fi.useDelimiter("[^\\p,\\.-]"); while (true)
If you want to use comma as a floating point delimiter, use fi.useLocale(Locale.FRANCE);
String sanitizedText = text.replaceAll("[^\\w\\s\\.]", "");
SanitizedText will contain only alphanumerics and whitespace; tokenizing it after that should be a breeze.
Edited to retain the decimal point as well (at the end of the bracket). . is «special» to regexp so it needs a backslash escape.
String onlyNumericText = text.replaceAll("\\\D", "");
String str = "1,222"; StringBuffer sb = new StringBuffer(); for(int i=0; i return sb.toString()
Java — Extract strings with Regex, The regular expression means «a string containing a word, a space, one or more digits (which are captured in group 1), a space, a set of words and spaces ending with a space, followed by a time (captured in group 2, and the time assumes that hour is always 0-padded out to 2 digits).
Java Scanner get number from string
The string is, for example «r1» and I need the 1 in an int form
Scanner sc = new Scanner("r1"); int result = sc.nextInt(); // should be 1
compiles correctly but has a runtime error, should I be using the delimiter? Im unsure what the delimiter does.
Well, there’s a few options. Since you literally want to skip the «r» then read the number, you could use Scanner#skip . For example, to skip all non-digits then read the number:
Scanner sc = new Scanner("r1"); sc.skip("[^0-9]*"); int n = sc.nextInt();
That will also work if there are no leading non-digits.
Another option is to use non-digits as delimiters, as you mentioned. For example:
Scanner sc = new Scanner("x1 r2kk3 4 x56y 7g"); sc.useDelimiter("[^0-9]+"); // note we use + not * while (sc.hasNextInt()) System.out.println(sc.nextInt());
Outputs the six numbers: 1, 2, 3, 4, 56, 7.
And yet another option, depending on the nature of your input, is to pre-process the string by replacing all non-digits with whitespace ahead of time, then using a scanner in its default configuration, e.g.:
String input = "r1"; input = input.replaceAll("[^0-9]+", " ");
And, of course, you could always just pre-process the string to remove the first character if you know it’s in that form, then use the scanner (or just Integer#parseInt ):
String input = "r1"; input = input.substring(1);
What you do depends on what’s most appropriate for your input. Replace «non-digit» with whatever it is exactly that you want to skip.
By the way I believe a light scolding is in order for this:
Im unsure what the delimiter does.
The documentation for Scanner explains this quite clearly in the intro text, and even shows an example.
Additionally, the definition of the word «delimiter» itself is readily available.
There are some fundamental mistakes here.
No it doesn’t. If sc is really a java.util.Scanner , then there is no Scanner.nextInt(String) method, so that cannot compile.
The second problem is that the hasNextXXX and nextXXX methods do not parse their arguments. They parse the characters in the scanner’s input source.
The third problem is that Scanner doesn’t provide a single method that does what you are (apparently) trying to do.
If you have a String s that contains the value «r1» , then you don’t need a Scanner at all. What you need to do us something like this:
String s = . int i = Integer.parseInt(s.substring(1));
Matcher m = Pattern.compile("r(\\d+)").matcher(s); if (m.matches())
. which checks that the field is in the expected format before extracting the number.
On the other hand if you are really trying to read the string from a scanner them, you could do something like this:
and then extract the number as above.
If the formatting is the same for all your input where the last char is the value you could use this:
String s = sc.nextLine() Int i = Integer.parseInt(s.charAt(s.length() -1));
Else you could for instance make the string a char Array, iterate trough it and check whether each char is a number.
Java Program to Count Number of Digits in a String, Examples: Input : string = «GeeksforGeeks password is : 1234» Output: Total number of Digits = 4 Input : string = «G e e k s f o r G e e k 1234» Output: Total number of Digits = 4 Approach: Create one integer variable and initialize it with 0. Start string traversal. If the ASCII code of character at the …
How to filter out numbers from a string in java?
I have a string of the following form for instance -:
String str = "The game received average review scores of 96.92% and 98/100 for the Xbox 360 version";
and I want the output as follows -:
Output = "The game received average review scores of % and / for the Xbox version"
and I want to be able to filter out any number that’s there in the string whether its a decimal or a floating point number, I tried using a brute force way of doing this like this -:
String str = "The game received average review scores of 96.92% and 98/100 for the Xbox 360 version"; String newStr = ""; for(int i = 0 ; i < str.length() ; ++i)< if(!Character.isDigit(str.charAt(i))) newStr += str.charAt(i); >System.out.println(newStr);
but this doesn’t solve the purpose for me, how to go about solving this problem?
You can use following String#replaceAll call to replace all numbers (followed by 0 or more spaces) by an empty string:
You can perhaps use something like this:
How to split numbers from a string in Java?, So here is what you can do: Scan every character. Check if the char is number. If yes, put in stack. Continue adding the char to stack until you get any non-numeric character. Once you get non-numeric character, take out all numeric chars from stack and convert to number. Continue till the char is not finished. …