How to read RegEx Captures in C#(如何在 C# 中读取正则表达式捕获)
问题描述
我开始编写一本 C# 书籍,并决定将 RegEx 加入其中,让枯燥的控制台练习变得更有趣.我想要做的是在控制台中向用户询问他们的电话号码,对照正则表达式进行检查,然后捕获数字,以便我可以按照我想要的方式对其进行格式化.除了 RegEx 捕获部分之外,我已经完成了所有工作.如何将捕获值放入 C# 变量中?
I started a C# book and I decided to throw RegEx's into the mix to make the boring console exercises a little more interesting. What I want to do is ask a user for their phone number in the console, check it against a RegEx, then capture the digits so I can format them the way I want. I've got all that working except the RegEx capture part. How do I get the capture values into C# variables?
还可以随时更正任何代码格式或变量命名问题.
Also feel free to correct any code formatting or variable naming issues.
static void askPhoneNumber()
{
String pattern = @"[(]?(d{3})[)]?[ -.]?(d{3})[ -.]?(d{4})";
System.Console.WriteLine("What is your phone number?");
String phoneNumber = Console.ReadLine();
while (!Regex.IsMatch(phoneNumber, pattern))
{
Console.WriteLine("Bad Input");
phoneNumber = Console.ReadLine();
}
Match match = Regex.Match(phoneNumber, pattern);
Capture capture = match.Groups.Captures;
System.Console.WriteLine(capture[1].Value + "-" + capture[2].Value + "-" + capture[3].Value);
}
推荐答案
C# regex API 可能相当混乱.有groups和captures:
The C# regex API can be quite confusing. There are groups and captures:
- 一个group代表一个捕获组,用于从文本中提取子串
- 如果组出现在量词内,则每个组可以有多个捕获.
- A group represents a capturing group, it's used to extract a substring from the text
- There can be several captures per group, if the group appears inside a quantifier.
层次结构是:
- 匹配
- 集团
- 拍摄
(一个匹配可以有多个组,每个组可以有多个捕获)
(a match can have several groups, and each group can have several captures)
例如:
Subject: aabcabbc Pattern: ^(?:(a+b+)c)+$在本例中,只有一组:
(a+b+).该组位于量词内,并匹配两次.它生成两个捕获:aab和abb:In this example, there is only one group:
(a+b+). This group is inside a quantifier, and is matched twice. It generates two captures:aabandabb:aabcabbc ^^^ ^^^ Cap1 Cap2当组不在量词内时,它只会生成一次捕获.在您的情况下,您有 3 个组,每个组捕获一次.您可以使用
match.Groups[1].Value、match.Groups[2].Value和match.Groups[3].Value提取您感兴趣的 3 个子字符串,而完全不诉诸 capture 概念.When a group is not inside of a quantifier, it generates only one capture. In your case, you have 3 groups, and each group captures once. You can use
match.Groups[1].Value,match.Groups[2].Valueandmatch.Groups[3].Valueto extract the 3 substrings you're interested in, without resorting to the capture notion at all.这篇关于如何在 C# 中读取正则表达式捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
- 集团
本文标题为:如何在 C# 中读取正则表达式捕获
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
