2

I have got strings like:

BLAH00001

DIK-11

DIK-2

MAN5

so all the strings are a kind of (sequence any characters)+(sequence of numbers)

and i want something like this:

1

11

2

5

in order to get those integer values, i wanted to separate the char sequence and the number sequence an do something like Integer.parseInt(number_sequence)

Is there something that does this job?

greetings

4 Answers 4

4

Try this:

public class Main {
    public static void main(String[]args) {
        String source = "BLAH00001\n" +
                "\n" +
                "DIK-11\n" +
                "\n" +
                "DIK-2\n" +
                "\n" +
                "MAN5";
        Matcher m = Pattern.compile("\\d+").matcher(source);
        while(m.find()) {
            int i = Integer.parseInt(m.group());
            System.out.println(i);
        }
    }
}

which produces:

1
11
2
5
Sign up to request clarification or add additional context in comments.

Comments

2
String[] a ={"BLAH00001","DIK-11","DIK-2","MAN5"};
 for(String g:a)
  System.out.println(Integer.valueOf(g.split("^[A-Z]+\\-?")[1]));

 /*******************************  
   Regex Explanation :
     ^  --> StartWith
    [A-Z]+ --> 1 or more UpperCase
    \\-? --> 0 or 1 hyphen   
*********************************/

Comments

1
 Pattern p = Pattern.compile("^[^0-9]*([0-9]+)$");
 Matcher m = p.matcher("ASDFSA123");
 if (m.matches()) {
    resultInt = Integer.parseInt(m.group(1)));
 }

2 Comments

That won't do it. Try it with the string in the original post, or something like "foo 123 bar 456 baz". With a Pattern/Matcher, you only need to define the pattern you want to match and then keep calling find() on the Matcher inside a while-statement.
You may be right, it is not clear to me from the post if the goal is to parse one string at a time or the whole thing at once.
0

Maybe you want to have a look to Java Pattern and Matcher:

1 Comment

This is nigh on RTFM. It is better to provide more guidance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.