我需要解析一些大的文本文件,并提取显示名称
和区号
,仅当它与以下模式匹配时:
- 行以
显示名称
开头(任意数量的单词,但不能包含数字或特殊字符) - 后跟6个数字(可以包含空格)
- 后跟
#text
标记
输入文件
John doe 123 456 #text some text
Test 123456 #text
Test$test 123456 #text
Test123 345678 #text
Test 123 #test
Test 123456 #test1
Test 123g45 #test
输入和期望输出
John doe 123 456 #text some text
Display name: John doe
Area code: 123 456
Test 123456 #text
Display name: Test
Area code: 123456
Test$test 123456 #text
Invalid, display name contains special character
Test123 345678 #text
Invalid, display name contains digits
Test 123 #test
Invalid, area code contains only 3 digits
Test 123456 #test1
Invalid, contains invalid tag
Test 123g45 #test
Invalid, area code contains letters
我知道如何打开文本文件并逐行读取,但是在编写正则表达式时遇到了困难。
以下是我尝试过的内容:
private static void Main(string[] args)
{
string text = "John Doe 123 45 #text Lorem ipsum dolor :)";
string pattern = @"(\w+)*([0-9]{2,5}).([0-9]{2,5}).#text";
Match match = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string key = match.Groups[0].Value;
Console.WriteLine(key);
}
}
编辑:
下面有更详细的解释。
显示名称
显示名称可以包含任意数量的单词,例如John Michael Smith
是有效的,因为John
是名字,Michael
是中间名,Smith
是姓氏。 Šljaker
也是有效的显示名称,因为它是某人的昵称,可能包含非英语字符。但是带数字的名称无效,例如John1
。为什么?这是我们的业务规则,不能有数字:)我想\w
在这里会起作用,而a-zA-Z
不会,因为它不包括非英语字母。
区号
业务规则很简单:它必须包含6个数字,我们不关心它们的格式。
所有这些都是有效的区号:123456、12 34 56、1234 56等。正则表达式不需要修剪空格,我会在代码中处理它们。
非常感谢您的帮助!