-1

I have a string that I am looking up that can have two possible values:

  1. stuff 1
  2. grouped stuff 1-3

I am not very familiar with using regex, but I know it can be very powerful when used correctly. So forgive me if this question sounds ridiculous in anyway. I was wondering if it would be possible to have some sort of regex code that would only leave the numbers of my string (for example in this case 1 and 1-3) but perhaps if it were the example of 1-3 I could just return the 1 and 3 separately to pass into a function to get the in between.

I hope I am making sense. It is hard to put what I am looking for into words. If anyone needs any further clarification I would be more than happy to answer questions/edit my own question.

scapegoat17
  • 5,509
  • 14
  • 55
  • 90

3 Answers3

2

To create a list of numbers in string y, use the following:

var listOfNumbers = Regex.Matches(y, @"\d+")
                           .OfType<Match>()
                           .Select(m => m.Value)
                           .ToList();
Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
Leslie Davies
  • 4,052
  • 1
  • 16
  • 14
0

This is fully possible, but best done with two separate Regexes, say SingleRegex and RangedRegex - then check for one or the other, and pass into a function when the result is RangeRegex.

As long as you're checking for "numbers in a specific place" then extra numbers won't confuse your algorythm. There are also several Regex Testers out there, a simple google Search weill give you an interface to check for various syntax and matches.

David
  • 10,458
  • 1
  • 28
  • 40
0

Are you just wanting to loop through all of the numbers in the string?

Here's one way you can loop throw each match in a regular expression.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        Regex r = new Regex(@"\d+");
        string s = "grouped stuff 1-3";

        Match m = r.Match(s);

        while(m.Success) 
        {
            string matchText = m.Groups[0].Value;
            Console.WriteLine(matchText);
            m = m.NextMatch();
        }   
    }

}

This outputs

1

3

Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205