简体   繁体   English

正则表达式可以从字符串中提取多个数字吗?

[英]Can Regex Extract Multiple Numbers from String?

Let's say I have a string like: 假设我有一个类似的字符串:

SORT_123_456 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. 我知道我可以逐个字符地解析,但是我想知道Regex是否可以处理这个问题。

I just haven't really used regular expressions. 我只是没有真正使用过正则表达式。 Can someone tell me if this can be done more easily using Regex ? 有人可以告诉我使用Regex是否可以更轻松地完成此操作?

SORT_(\\d+)_(\\d+) will do it. SORT_(\\d+)_(\\d+)将执行此操作。 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+) . 如果用另一个单词替换SORT,则\\w+_(\\d+)_(\\d+)会这样做,如果完全丢失,则(\\d+)_(\\d+)将是正则表达式,最后,如果单词必须大写: [AZ]+_(\\d+)_(\\d+)

If you want an example using the Split() Function here is what you could do 如果您想要使用Split()函数的示例,则可以这样做

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 或者您可以检查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()
          ;
}

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

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