3

I want to split a string like "001A" into "001" and "A"

6 Answers 6

4
string[] data = Regex.Split("001A", "([A-Z])");
data[0] -> "001"
data[1] -> "A"
Sign up to request clarification or add additional context in comments.

3 Comments

String.Split doesn't take a regex, as far as I know.
Did you test it? It should be Regex.Split("001A", "([A-Z])"), or the group is removed (as a divider).
this works, but it gives a string array of 3 elements. the last element is empty.
4
Match match = Regex.Match(s, @"^(\d+)(.+)$");
string numeral = match.Groups[1].Value;
string tail = match.Groups[2].Value;

3 Comments

. matches anything, you should restrict to \w or [a-zA-Z]
@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.
the title of the question is »how to split numerics and alphabets« ;) but nevermind, in the given example your solution will give correct results
2

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

1

If your code is as simple|complicated as your 001A sample, your should not be using a Regex but a for-loop.

Comments

0

And if there's more like 001A002B then you could

    var s = "001A002B";
    var matches = Regex.Matches(s, "[0-9]+|[A-Z]+");
    var numbers_and_alphas = new List<string>();
    foreach (Match match in matches)
    {
        numbers_and_alphas.Add(match.Value);
    }

Comments

0

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.

Comments

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.