Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Integer Part in String

Tags:

What is the best way to extract the integer part of a string like

Hello123 

How do you get the 123 part. You can sort of hack it using Java's Scanner, is there a better way?

like image 964
Verhogen Avatar asked Dec 14 '09 20:12

Verhogen


People also ask

How do you extract an int from a string in Python?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.

How do I isolate part of a string in Java?

You can extract a substring from a String using the substring() method of the String class to this method you need to pass the start and end indexes of the required substring.


2 Answers

As explained before, try using Regular Expressions. This should help out:

String value = "Hello123"; String intValue = value.replaceAll("[^0-9]", ""); // returns 123 

And then you just convert that to an int (or Integer) from there.

like image 181
Ascalonian Avatar answered Oct 08 '22 06:10

Ascalonian


I believe you can do something like:

Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+"); int integer = in.nextInt(); 

EDIT: Added useDelimiter suggestion by Carlos

like image 25
Brian Hasden Avatar answered Oct 08 '22 08:10

Brian Hasden