简体   繁体   English

用正则表达式拆分

[英]Splitting with Regex

I want to split strings similar to abc123 , abcdefgh12 or a123456 into letters and numbers, so that the result will be {"abc", "123"} etc. 我想将类似于abc123abcdefgh12a123456字符串a123456为字母和数字,以便结果为{"abc", "123"}等。

What is the simplest way to do it in C# 4.0? 在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);
    }

"Only numbers or only letters" can be represented using [a-zA-Z]*|[0-9]* . 可以使用[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"} ). 请注意,将不会返回非字母数字字符,但仍会拆分字符串(因此, "123-456"将产生{ "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. 编辑 :我将您的问题解释为,您的字符串可以是任意顺序的字母和数字序列-如果您的字符串只是一个或多个字母后跟一个或多个数字,则不需要使用正则表达式:第一位数字并分割字符串。

In addition to Marc Gravell, read http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html . 除了Marc Gravell外,请阅读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? 在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. 用固定模式分割的最简单方法不是使用正则表达式。

splitArray = Regex.Split(myString, @"(?<=\p{L})(?=\p{N})");

正则表达式拆分字符串和数字

除非我缺少任何东西,否则应该可以解决... ([az]*)([0-9]*)

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! 有关更多信息, 使用本指南: http : //www.regular-expressions.info/reference.html HTH!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM