简体   繁体   English

如何使用正则表达式拆分字符串以返回值列表?

[英]How can I split a string using regex to return a list of values?

How can I take the string foo[]=1&foo[]=5&foo[]=2 and return a collection with the values 1,5,2 in that order. 如何获取字符串foo[]=1&foo[]=5&foo[]=2 1,5,2该顺序返回值1,5,2的集合。 I am looking for an answer using regex in C#. 我正在寻找在C#中使用正则表达式的答案。 Thanks 谢谢

In C# you can use capturing groups 在C#中,您可以使用捕获组

    private void RegexTest()
    {
        String input = "foo[]=1&foo[]=5&foo[]=2";
        String pattern = @"foo\[\]=(\d+)";

        Regex regex = new Regex(pattern);

        foreach (Match match in regex.Matches(input))
        {
            Console.Out.WriteLine(match.Groups[1]);
        }
    }

I don't know C#, but... 我不懂C#,但是...

In java: 在Java中:

String[] nums = String.split(yourString, "&?foo[]");

The second argument in the String.split() method is a regex telling the method where to split the String. String.split()方法中的第二个参数是一个正则表达式,告诉该方法在哪里拆分String。

Use the Regex.Split() method with an appropriate regex. 将Regex.Split()方法与适当的regex一起使用。 This will split on parts of the string that match the regular expression and return the results as a string[]. 这将拆分与正则表达式匹配的字符串部分,并将结果作为string []返回。

Assuming you want all the values in your querystring without checking if they're numeric, (and without just matching on names like foo[]) you could use this: "&?[^&=]+=" 假设您想要查询字符串中的所有值而不检查它们是否为数字,(并且不仅仅与foo []之类的名称匹配),可以使用以下命令:“&?[^&=] + =”

string[] values = Regex.Split(“foo[]=1&foo[]=5&foo[]=2”, "&?[^&=]+=");

Incidentally, if you're playing with regular expressions the site http://gskinner.com/RegExr/ is fantastic (I'm just a fan). 顺便说一句,如果您正在使用正则表达式,则该网站http://gskinner.com/RegExr/非常棒(我只是一个粉丝)。

I'd use this particular pattern: 我将使用以下特定模式:

string re = @"foo\[\]=(?<value>\d+)";

So something like (not tested): 所以像(未经测试):

Regex reValues = new Regex(re,RegexOptions.Compiled);
List<integer> values = new List<integer>();

foreach (Match m in reValues.Matches(...putInputStringHere...)
{
   values.Add((int) m.Groups("value").Value);
}

假设您正在处理数字,则此模式应匹配:

/=(\d+)&?/

This should do: 应该这样做:

using System.Text.RegularExpressions;

Regex.Replace(s, !@"^[0-9]*$”, "");

Where s is your String where you want the numbers to be extracted. 其中s是您要提取数字的字符串。

只需确保像这样逃脱“&”号即可:

/=(\d+)\&/

Here's an alternative solution using the built-in string.Split function: 这是使用内置string.Split函数的替代解决方案:

string x = "foo[]=1&foo[]=5&foo[]=2";
string[] separator = new string[2] { "foo[]=", "&" };
string[] vals = x.Split(separator, StringSplitOptions.RemoveEmptyEntries);

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

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