I want to split a string like "001A" into "001" and "A"
6 Answers
string[] data = Regex.Split("001A", "([A-Z])");
data[0] -> "001"
data[1] -> "A"
Match match = Regex.Match(s, @"^(\d+)(.+)$");
string numeral = match.Groups[1].Value;
string tail = match.Groups[2].Value;
3 Comments
knittl
. matches anything, you should restrict to \w or [a-zA-Z]Kobi
@knittl - I know,
. is ok as long as the OP doesn't need to validate it. The question doesn't have enough details so I went with this.knittl
the title of the question is »how to split numerics and alphabets« ;) but nevermind, in the given example your solution will give correct results
This is Java, but it should be translatable to other flavors with little modification.
String s = "123XYZ456ABC";
String[] arr = s.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
System.out.println(Arrays.toString(arr));
// prints "[123, XYZ, 456, ABC]"
As you can see, this splits a string wherever \d is followed by a \D or vice versa. It uses positive and negative lookarounds to find the places to split.
Comments
You could try something like this to retrieve the integers from the string:
StringBuilder sb = new StringBuilder();
Regex regex = new Regex(@"\d*");
MatchCollection matches = regex.Matches(inputString);
for(int i=0; i < matches.count;i++){
sb.Append(matches[i].value + " ");
}
Then change the regex to match on characters and perform the same loop.