Question

I want to split a string so that I get starting alphabetical string(until the first numeric digit occured). And the other alphanumeric string.

E.g.: I have a string forexample: Nesc123abc456

I want to get following two strings by splitting the above string: Nesc, 123abc456

What I have tried:

    String s = "Abc1234avc";
    String[] ss = s.split("(\\D)", 2);

    System.out.println(Arrays.toString(ss));

But this just removes the first letter from the string.

Was it helpful?

Solution

You could maybe use lookarounds so that you don't consume the delimiting part:

String s = "Abc1234avc";
String[] ss = s.split("(?<=\\D)(?=\\d)", 2);

System.out.println(Arrays.toString(ss));

ideone demo

(?<=\\D) makes sure there's a non-digit before the part to be split at,

(?=\\d) makes sure there's a digit after the part to be split at.

OTHER TIPS

You need the quantifier.

Try

String[] ss = s.split("(\\D)*", 2);

More information here: http://docs.oracle.com/javase/tutorial/essential/regex/quant.html

Didn't you try replaceAll?

String s = ...;
String firstPart = s.replaceAll("[0-9].*", "");
String secondPart = s.substring(firstPart.length());

You can use:

String[] arr = "Nesc123abc456".split("(?<=[a-zA-Z])(?![a-zA-Z])", 2);
//=> [Nesc, 123abc456]

split is a destructive process so you would need to find the index of the first numeric digit and use substrings to get your result. This would also probably be faster than using a regex since those have a lot more heuristics behind them

int split = string.length();
for(int i = 0; i < string.length(); i ++) {
    if (Character.isDigit(string.charAt(i)) {
        split = i;
        break;
    }
}
String[] parts = new String[2];
parts[0] = string.substring(0, split);
parts[1] = string.substring(split);

I think this is what you asked:

String s = "Abc1234avc";
String numbers = "";
String chars = "";
for(int i = 0; i < s.length(); i++){
    char c = s.charAt(i);
    if(Character.isDigit(c)){
        numbers += c + "";
    }
    else {
        chars += c + "";
    }
}

System.out.println("Numbers: " + numbers + "; Chars: " + chars);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top