开发者

How to split string into numerics and alphabets using Regex

I want to split a string like "001A" into "001" and 开发者_开发知识库"A"


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;


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.


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜