0

Let's say there are three strings:

String s1 = "6A";
String s2 = "14T";
String s3 = "S32";

I need to extract numeric values (i.e. 6,14 and 32) and characters (A,T and S).

If the first character was always a digit, then this code would work:

int num = Integer.parseInt(s1.substring(0,1));

However, this is not applicable to s2 and s3.

Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217
  • you can for example use `s1.replaceAll("\\D+","");` to remove all non-digits from string. – NeplatnyUdaj Mar 02 '15 at 11:31
  • Consider something like `String.replaceAll()` ([docs](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html)) to strip all non-numeric characters from each string before parsing the values. – ctt Mar 02 '15 at 11:35
  • 1
    This question has been answered previously here: http://stackoverflow.com/questions/4030928/extract-digits-from-a-string-in-java – Henry Vonfire Mar 02 '15 at 11:39

4 Answers4

4

You can make something like that:

public static int getNumber(String text){
    return Integer.parseInt(text.replaceAll("\\D", ""));
}

public static String getChars(String text){
    return text.replaceAll("\\d", "");
}

public static void main(String[] args) {
    String a = "6A";
    String b = "14T";
    String c = "S32";

    System.out.println(getNumber(a));
    System.out.println(getChars(a));
    System.out.println(getNumber(b));
    System.out.println(getChars(b));
    System.out.println(getNumber(c));
    System.out.println(getChars(c));
}

Output:

6 A 14 T 32 S

pL4Gu33
  • 2,045
  • 16
  • 38
3

Try this:

String numberOnly = s1.replaceAll("[^0-9]", "");
int num = Integer.parseInt(numberOnly);

Or the short one:

int num = Integer.parseInt(s1.replaceAll("[^0-9]", ""));

The code is applicable for s2 and s3 as well!

P Griep
  • 846
  • 2
  • 14
  • 26
1

You can use java.util.regex package which is consists two most important classes

1) Pattern Class

2) Matcher Class

Using this classes to get your solution.

For more details about Pattern and Matcher Class refer below link

http://www.tutorialspoint.com/java/java_regular_expressions.htm

Below is the complete example

public class Demo {
public static void main(String[] args) {
    String s1 = "6A";
    String s2 = "14T";
    String s3 = "S32";

    Pattern p = Pattern.compile("-?\\d+");
    Matcher m = p.matcher(s3);
    while (m.find()) 
    {
        System.out.println(m.group());
    }

}
}

If you need string and wants to skip numeric value then use below pattern.

Pattern p = Pattern.compile("[a-zA-Z]");
-2

Yo can check whether first character in a string is a letter if yes then do

Integer.parseInt(s1.substring(1))

Means parse from second character

maxormo
  • 599
  • 1
  • 4
  • 10