开发者

Splitting with Regex [duplicate]

开发者 https://www.devze.com 2023-02-03 09:08 出处:网络
This question already has answers here: Regular expression to split string and number (8 answers) 开发者_高级运维
This question already has answers here: Regular expression to split string and number (8 answers) 开发者_高级运维 Closed 2 years ago.

I want to split strings similar to abc123, abcdefgh12 or a123456 into letters and numbers, so that the result will be {"abc", "123"} etc.

What is the simplest way to do it in C# 4.0? I want to do it with one regex.


Why regex?

    static readonly char[] digits = {'0','1','2','3','4','5','6','7','8','9'};
    ....
    string s = "abcdefgh12", x = s, y = "";
    int i = s.IndexOfAny(digits);
    if (i >= 0) {
        x = s.Substring(0, i);
        y = s.Substring(i, s.Length - i);
    }


In addition to Marc Gravell, read http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html .

What is the simplest way to do it in C# 4.0? I want to do it with one regex.

That's practically an oxymoron in your case. The simplest way of splitting by a fixed pattern is not with regexes.


Unless I'm missing something, this should do the trick... ([a-z]*)([0-9]*)


"Only numbers or only letters" can be represented using [a-zA-Z]*|[0-9]*. All you have to do is look for all matches of that regular expression in your string. Note that non-alphanumeric characters will not be returned, but will still split the strings (so "123-456" would yield { "123", "456"}).

EDIT: I've interpreted your question as stating that your strings can be a sequence of letters and numbers in any order - if your string is merely one or more letters followed by one or more numbers, a regular expression is unnecessary: look for the first digit and split the string.


You could create a group for letteres and one for numbers. use this guide for further info: http://www.regular-expressions.info/reference.html HTH!

0

精彩评论

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

关注公众号