简体   繁体   中英

Can Regex Extract Multiple Numbers from String?

Let's say I have a string like:

SORT_123_456

Is there an easy way to parse the two integer values? I do not know how many digits these values will have. It would also be helpful if I could validate the other characters and just abandon the parsing if they don't appear as I have them above (that would indicate something is wrong).

I know I can parse character by character, but I was wondering if Regex could handle this.

I just haven't really used regular expressions. Can someone tell me if this can be done more easily using Regex ?

SORT_(\\d+)_(\\d+) will do it. Just extract the two groups after using your regex.

If SORT is remplaced by an other word, then \\w+_(\\d+)_(\\d+) will do it, if it is totally missing, (\\d+)_(\\d+) will be the regex, and finally, if the word must be in Caps : [AZ]+_(\\d+)_(\\d+) .

If you want an example using the Split() Function here is what you could do

var splitStr = "SORT_123_456";
var sortable = splitStr.Split('_');
if (sortable[0].Contains("SORT"))
{
    //do your sorting logic because you have a sortable 
    sortable[1] //will be "123"
    sortable[2] //will be "456"
}

or you could check for string.Empty

var splitStr = "SORT_123_456";
var sortable = splitStr.Split('_');
if (!sortable[0] == string.Empty)
{
    //do your sorting logic because you have a sortable 
    sortable[1] //will be "123"
    sortable[2] //will be "456"
}

This is the simple way. One simple regular expression. It validates the source string and extracts and captures all the the numeric fields, regardless of number of such fields found:

string src = @"SORT_123_456_789" ;
Regex  rx = new Regex( @"^SORT(_\d+)*$" ) ;
Match  match = rx.Match( src ) ;

if ( !match.Success ) throw new InvalidOperationException() ;

int[] values = null ;
if ( match.Success )
{
  values = match
          .Groups[1]
          .Captures
          .Cast<Capture>()
          .Select( c => int.Parse( c.Value.Substring(1) ) )
          .ToArray()
          ;
}

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