简体   繁体   English

有人可以帮我解决一些正则表达式吗?

[英]Can someone help me out with some regex?

I'm trying to get an int[] from the following string.我正在尝试从以下字符串中获取一个int[] I was initially doing a Regex().Split() but as you can see there isn't a definite way to split this string.我最初是在做Regex().Split()但是你可以看到没有一个明确的方法来分割这个字符串。 I could split on [az] but then I have to remove the commas afterwards.我可以在[az]上拆分,但之后我必须删除逗号。 It's late and I can't think of a nice way to do this.已经很晚了,我想不出一个好的方法来做到这一点。

"21,false,false,25,false,false,27,false,false,false,false,false,false,false,false"

Any suggestions?有什么建议么?

Split on the following:拆分如下:

[^\d]+

You may get an empty element at the beginning if your string doesn't begin with a number and/or an empty element at the end if your string doesn't end with a number.如果您的字符串不以数字开头,您可能会在开头得到一个空元素和/或如果您的字符串不以数字结尾,则在结尾处可能会得到一个空元素。 If this happens you can trim those elements.如果发生这种情况,您可以修剪这些元素。 Better yet, if Regex().Split() supports some kind of flag to not return empty strings, use that.更好的是,如果Regex().Split()支持某种标志以不返回空字符串,请使用它。

A simple solution here is to match the string with the pattern \d+ .这里一个简单的解决方案是将字符串与模式\d+匹配。 Sometimes it is easier to split by the values you don't want to match, but here it serves as an anti-pattern.:有时更容易按您不想匹配的值进行拆分,但在这里它用作反模式。:

MatchCollection numbers = Regex.Matches(s, @"\d+");

Another solution is to use regular String.Split and some LINQ magic.另一种解决方案是使用常规 String.Split 和一些 LINQ 魔法。 First we split by commas, and then check that all letters in a given token are digits:首先我们用逗号分隔,然后检查给定标记中的所有字母是否都是数字:

var numbers = s.Split(',').Where(word => word.All(Char.IsDigit));

It is an commonly ignored fact the \d in.Net matches all Unicode digits , and not just [0-9] (try ١٢٣ in your array, just for fun).这是一个通常被忽略的事实\d in.Net 匹配所有 Unicode 数字,而不仅仅是[0-9] (尝试 ١٢٣ 在您的数组中,只是为了好玩)。 A more robust solution is to try to parse each token according to your defined culture, and return the valid numbers.一个更强大的解决方案是尝试根据您定义的文化解析每个标记,并返回有效数字。 This can easily be adapted to support decimals, exponents or ethnic numeric formats:这可以很容易地适应支持小数、指数或民族数字格式:

static IEnumerable<int> GetIntegers(string s)
{
    CultureInfo culture = CultureInfo.InvariantCulture;
    string[] tokens = s.Split(',');
    foreach (string token in tokens)
    {
        int number;
        if (Int32.TryParse(token, NumberStyles.Integer, culture, out number))
            yield return number;
    }
}

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

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