正则表达式在引号中查找组匹配

时间:2014-01-27 03:15:32

标签: c# regex expression

我正在努力使用正则表达式在单引号中找到该组文本。我需要你的建议如何获得它。

输入文字:

Transfer assignee from 'David, Patricia' to ''
Transfer group from 'Science Department - Support Group' to 'Science Department - Human Resources '

要求:我需要从单引号中提取组并将其分组,并将其保存在数据库中。

我试过但总是空洞的结果。这是代码

 public void ExtractGroup(string text)
    {
        var match = Regex.Match(text, @" group from '([^']*)" to '([^']*)", RegexOptions.IgnoreCase);

        if(match.Success) {
             var groupfrom = match.Groups[1].Value;
             var groupTo = match.Groups[2].Value;
        }
    }

2 个答案:

答案 0 :(得分:2)

我尝试了你的代码,我发现它运行正常:

public static void ExtractGroup()
{
    string input = "Transfer assignee from 'David, Patricia' to '' Transfer group from 'Science Department - Support Group' to 'Science Department - Human Resources '";
    var match = Regex.Match(input, @" group from '(?<from>[^']*)' to '(?<to>[^']*)'", RegexOptions.IgnoreCase);

    if (match.Success)
    {
        Console.WriteLine(match.Groups["from"]); // Science Department - Support Group
        Console.WriteLine(match.Groups["to"]); // Science Department - Human Resources
    }            
}

但是,我在C#Console应用程序中运行它。但我不认为它会有任何不同。

答案 1 :(得分:0)

鉴于此输入:

Transfer assignee from 'David, Patricia' to '' Transfer group from 'Science Department - Support Group' to 'Science Department - Human Resources '

根据你的描述:

 to extract the group from and group to in the single quote

您希望输出为这两个字符串:

Science Department - Support Group
Science Department - Human Resources

我希望像这样的正则表达式能够起作用:

 to .*?'(.*?)' to '(.*?)'

但是,我可能会更加完整,因为您可能希望稍后整个数据集:

Transfer (.*?) from '(.*?)' to '(.*?)' Transfer (.*?) from '(.*?)' to '(.*?)'

你得到的方式:

1: transfer type 1 - 'assignee'
2: transfer from 1 - 'David, Patricia'
3: transfer to 1   - ''
4: transfer type 2 - 'group'
5: transfer from 2 - 'Science Department - Support Group'
6: transfer to 2   - 'Science Department - Human Resources '

或者,您可以使用Transfer (.*?) from '(.*?)' to '(.*?)'正则表达式对此进行抽象,并将其多次应用于字符串,直到传输类型等于group。通过这种方式,您可以稍后为其他传输类型添加逻辑,并且字符串可以在其中声明任意数量的传输而不会有任何中断。