简体   繁体   中英

Regex match for comma delimited string

I have the following string which is legal.

1-5,10-15

Using the following regex, I get a false for match.

^[^-\s]*-?[^-\s]*$

It works fine for things like

  • 1-5,10
  • 1,5

which are all legal. But it won't handle comma delimited ranges. What am I missing?

where's the handling for a comma? try to visualize your regex in regexper

now try this:

^(\\d+-?\\d+)(?:\\,(\\d+-?\\d+))+$

来自regexper.com的截图

Update: my regex is not a solution as you might have very specific needs for the captures. However, that nifty tool might help you with the task once you see what your regex does.

Try this pattern,

^\d+(\-\d+)?(\,(\d+(\-\d+)?))*$

it will match on the following strings:

1-5,10-15,5
1,2,3-5,3-4
1-5,10-15
10-15
10-15,5

but not on

1-,10-15,5
1,2,3-5,3-
1-510-15
10-15,
,10-15,5

The best regex I know for splitting comma separated strings is:

",(?=(?:[^\""]*\""[^\""]*\"")*(?![^\""]*\""))"

It will not split an entry in quotations that contains commas.

Eg Hello, There, "You, People" gives

Hello

There

You, People

^(\s*\d+\s*-?\s*\d*)(\,(\s*\d+\s*-?\s*\d*))*$

It takes care of starting spaces, followed by at least 1 digit. "-" is optional and can be followed by one or more digits. "," is optional and can be followed by the same group as before.

Matches:

1,5

1-5,5-10

15,2,10,4-10

Here's an approach using just splits:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RangeTester
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "1,2,3,1-5,10-15,100-200";
            string[] ranges = str.Split(',');
            foreach (string range in ranges)
            {
                Console.WriteLine(GetRange(range.Trim()));
            }
            Console.Read();
        }

        static string GetRange(string range)
        {
            string[] rng = range.Split('-');
            if (rng.Length == 2)
                return rng[0] + " to " + rng[1];
            else
                return rng[0];
        }
    }
}

I was over thinking the solution to this problem, but since you know that your list of numbers/ranges will be first delimited by commas and then by dashes, you can use splits to parse out the individual parts. There is no need to use regular expressions for parsing this string.

试试这个正则表达式:

^\d+(-\d+)?(,\d+(-\d+)?)*$

You might want something like (\\d+)-(\\d+) to get every range. Example here .

I think this should also work fine.

^\d*(-\d*)?,\d*(-?\d*)?$

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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