首页 > 解决方案 > 基于字符串匹配的正则表达式提取字符串

问题描述

我有这些数据,其中包含一些杂乱的地址,其中有时不按省、区和病房的顺序排列:

Name        ADDRESS 
Store1      453, Duy Tan, Phuong Nguyen Nghiem, Thanh pho Quang Ngai
Store2      13 DUNG SY THANH KHE, P. THANH KHE TAY
Store3      98 Phan Xich Long- P. 2
Store4      306 B4, NGUYENVAN LINH, Ward - 5 
Store5      22, Ngo 421/16, Tran Duy Hung, To 42, Phuong Trung Hoa, Quan Cau Giay




    public override void Input0_ProcessInputRow(Input0Buffer Row)
    {
        //Replace each \ with \\ so that C# doesn't treat \ as escape character
        //Pattern: Start of string, any integers, 0 or 1 letter, end of word
        string sPattern = "^[0-9]+([A-Za-z]\\b)?";
        string sString = Row.ADDRESS ?? ""; //Coalesce to empty string if NULL

        //Find any matches of the pattern in the string
        Match match = Regex.Match(sString, sPattern, RegexOptions.IgnoreCase);
        //If a match is found
        if (match.Success)
            //Return the first match into the new
            //HouseNumber field
            Row.ward= match.Groups[0].Value;
        else
            //If not found, leave the HouseNumber blank
            Row.ward= "";
    }

}

我想修改我的正则表达式以在 Ward 列中返回这样的数据。(您可以在我的地址中看到同义词(Phuong、P.、ward 等)。

Name         ADDRESS                                                                  ward 
Store1      453, Duy Tan, Phuong Nguyen Nghiem, Quang Ngai                Phuong Nguyen Nghiem
Store2      13 DUNG SY THANH KHE, P. THANH KHE TAY                        Phuong THANH KHE TAY
Store3      98 Phan Xich Long- P. 2                                       Phuong 2
Store4      306 B4, NGUYENVAN LINH, Ward - 5                              Phuong 5
Store5      22, Ngo 421/16,--. To 42, Phuong Trung Hoa, Quan Cau Giay     Phuong Trung Hoa

我使用该正则表达式来提取公民号码,但是有没有一种方法可以使用正则表达式来修改我的列病房中的数据,就像上面的示例一样?

标签: regex

解决方案


如在https://regex101.com/中测试的,此正则表达式中的组与您的 column 中的数据相匹配ward,如您的示例中所示。但是,您可能需要更好地定义每个将出现的模式,因为此正则表达式仅与它们在示例数据中出现时匹配。但是,对您而言,推断并获得您真正需要的正则表达式可能就足够了。

(Phuong.*),|P\.(.*$)|Ward - (.*$)
  • 选项 1 中的组匹配从Phuong(含)到第一个逗号。
  • 选项 2 中的组匹配P.字符串末尾之后的任何内容。
  • 选项 3 中的组匹配Ward - 字符串末尾之后的任何内容。

这个有点高级,但它只匹配您在示例中提到的内容,没有组:

Phuong.*(?=,)|(?<=P\.).*$|(?<=Ward - ).*$

在https://regex101.com中对其进行测试以了解其工作原理以及每个部分的含义。

最后,您可能希望Phuong 从选项 1 中的匹配中排除,以便您的程序始终可以打印Phuong 然后匹配。


推荐阅读