regex - 基于字符串匹配的正则表达式提取字符串
问题描述
我有这些数据,其中包含一些杂乱的地址,其中有时不按省、区和病房的顺序排列:
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
我使用该正则表达式来提取公民号码,但是有没有一种方法可以使用正则表达式来修改我的列病房中的数据,就像上面的示例一样?
解决方案
如在https://regex101.com/中测试的,此正则表达式中的组与您的 column 中的数据相匹配ward
,如您的示例中所示。但是,您可能需要更好地定义每个将出现的模式,因为此正则表达式仅与它们在示例数据中出现时匹配。但是,对您而言,推断并获得您真正需要的正则表达式可能就足够了。
(Phuong.*),|P\.(.*$)|Ward - (.*$)
- 选项 1 中的组匹配从
Phuong
(含)到第一个逗号。 - 选项 2 中的组匹配
P.
字符串末尾之后的任何内容。 - 选项 3 中的组匹配
Ward -
字符串末尾之后的任何内容。
这个有点高级,但它只匹配您在示例中提到的内容,没有组:
Phuong.*(?=,)|(?<=P\.).*$|(?<=Ward - ).*$
在https://regex101.com中对其进行测试以了解其工作原理以及每个部分的含义。
最后,您可能希望Phuong
从选项 1 中的匹配中排除,以便您的程序始终可以打印Phuong
然后匹配。
推荐阅读
- javascript - 如何从对象创建数组?
- javascript - 无序列表项目符号未显示在预期位置
- python-2.7 - 在没有服务帐户凭据的情况下使用 python 在 Google Cloud 中创建一个新项目
- c++ - 包含 tlhelp32 头文件
- c - 在 C 程序中正确放置 volatile 修饰符 (Visual Studio)
- sql-server - SQL Server 2012 并发插入逻辑检查
- php - Laravel 只获取第一个相关模型
- linux - 允许 DOCKER-USER 链中的一些 IP 用于入站流量,拒绝所有其他 IP
- google-sheets - 谷歌表格 - 具有多个列的嵌入式数组
- laravel - Laravel 有计数的子查询,没有关系