user99322
user99322

Reputation: 1207

How to split string into numerics and alphabets using Regex

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

Upvotes: 3

Views: 1647

Answers (6)

polygenelubricants
polygenelubricants

Reputation: 383746

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.

Upvotes: 2

derek
derek

Reputation: 4886

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.

Upvotes: 0

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31428

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);
    }

Upvotes: 0

FireSnake
FireSnake

Reputation: 3163

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

Upvotes: 1

James
James

Reputation: 82096

string[] data = Regex.Split("001A", "([A-Z])");
data[0] -> "001"
data[1] -> "A"

Upvotes: 4

Kobi
Kobi

Reputation: 138017

Match match = Regex.Match(s, @"^(\d+)(.+)$");
string numeral = match.Groups[1].Value;
string tail = match.Groups[2].Value;

Upvotes: 4

Related Questions