正则表达式C# - 它是可以提取的比赛同时匹配? [英] Regular expressions C# - is it possible to extract matches while matching?

查看:137
本文介绍了正则表达式C# - 它是可以提取的比赛同时匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我说,我有一个字符串,我需要验证的正确格式;例如 RR1234566-001 (2个字母,7位数字,破折号,1个或多个数字)。我用的是这样的:

Say, I have a string that I need to verify the correct format of; e.g. RR1234566-001 (2 letters, 7 digits, dash, 1 or more digits). I use something like:

        Regex regex = new Regex(patternString);
        if (regex.IsMatch(stringToMatch))
        {
            return true;
        }
        else
        {
            return false;
        }

这作品告诉我是否 stringToMatch 遵循 patternString 定义的模式。我需要什么,但(我最终提取这些后来的)分别是:
123456 001 - IE的部分 stringToMatch

This works to tell me whether the stringToMatch follows the pattern defined by patternString. What I need though (and I end up extracting these later) are: 123456 and 001 -- i.e. portions of the stringToMatch.

请注意,这不是一个关于如何构建正则表达式的问题。我所问的是:有没有办法,而不必以后使用拆分功能,同时匹配和提取价值

Please note that this is NOT a question about how to construct regular expressions. What I am asking is: "Is there a way to match and extract values simultaneously without having to use a split function later?"

推荐答案

您可以使用正则表达式组来实现这一目标。例如,这个正则表达式:

You can use regex groups to accomplish that. For example, this regex:

(\d\d\d)-(\d\d\d\d\d\d\d)

让我们匹配一个电话号码此正则表达式:

Let's match a telephone number with this regex:

var regex = new Regex(@"(\d\d\d)-(\d\d\d\d\d\d\d)");
var match = regex.Match("123-4567890");
if (match.Success)
    ....

如果它匹配,你会发现前三个数字中:

If it matches, you will find the first three digits in:

match.Groups[1].Value

和第二个7位数:

match.Groups[2].Value

PS在C#中,你可以使用一个@样式的字符串,以避免转义反斜线。例如,@\hi\等于\\hi\\。有用的正则表达式和路径。

P.S. In C#, you can use a @"" style string to avoid escaping backslashes. For example, @"\hi\" equals "\\hi\\". Useful for regular expressions and paths.

P.S.2。第一组是存储在组[1],而不是集团[0]如你所愿。这是因为集团[0]包含整个匹配的字符串。

P.S.2. The first group is stored in Group[1], not Group[0] as you would expect. That's because Group[0] contains the entire matched string.

这篇关于正则表达式C# - 它是可以提取的比赛同时匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆