Reputation: 2185
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.
Upvotes: 0
Views: 85
Reputation: 855
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);
Upvotes: 0
Reputation: 13834
You need the quantifier.
Try
String[] ss = s.split("(\\D)*", 2);
More information here: http://docs.oracle.com/javase/tutorial/essential/regex/quant.html
Upvotes: 1
Reputation: 817
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);
Upvotes: 0
Reputation: 785196
You can use:
String[] arr = "Nesc123abc456".split("(?<=[a-zA-Z])(?![a-zA-Z])", 2);
//=> [Nesc, 123abc456]
Upvotes: 0
Reputation: 71538
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));
(?<=\\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.
Upvotes: 4
Reputation: 7461
Didn't you try replaceAll
?
String s = ...;
String firstPart = s.replaceAll("[0-9].*", "");
String secondPart = s.substring(firstPart.length());
Upvotes: 0