user17872
user17872

Reputation: 13

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. I am looking for an answer using regex in C#. Thanks

Upvotes: 1

Views: 8193

Answers (8)

Austin Salonen
Austin Salonen

Reputation: 50215

Here's an alternative solution using the built-in string.Split function:

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

Upvotes: 0

Rory
Rory

Reputation: 41807

Use the Regex.Split() method with an appropriate regex. This will split on parts of the string that match the regular expression and return the results as a 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: "&?[^&=]+="

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).

Upvotes: 1

torial
torial

Reputation: 13121

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

Upvotes: 1

Santiago Palladino
Santiago Palladino

Reputation: 3542

In C# you can use capturing groups

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

Upvotes: 4

Hans Sjunnesson
Hans Sjunnesson

Reputation: 22299

Just make sure to escape the ampersand like so:

/=(\d+)\&/

Upvotes: 0

Burkhard
Burkhard

Reputation: 14738

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.

Upvotes: 0

Anya Shenanigans
Anya Shenanigans

Reputation: 94614

Assuming you're dealing with numbers this pattern should match:

/=(\d+)&?/

Upvotes: 0

jjnguy
jjnguy

Reputation: 138874

I don't know C#, but...

In 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.

Upvotes: 1

Related Questions