如何忽略Regex.Match上的特定字符

时间:2020-08-04 03:20:30

标签: c# regex

嗨,这是我在这个论坛上的第一个问题,因为我自己没有找到解决方案,所以我决定寻求帮助

string pattern = @"Chapter\s?(.*):\s*(.*)";
var m = Regex.Match(input, pattern);

我一直在使用这种模式,但是并不是所有的字符串都具有相同的格式,我想知道是否有一种方法可以忽略“:”字符以使其起作用,或者是否有更好的方法< / p>

//Examples:
"Chapter 3.10:  Some Text"
"Chapter 2.2:  Some Text(2)"
"Chapter 1.20"

//Outputs
"3.10" "Some Text"
"2.2" "Some Text(2)"
"" "" 
// The last return nothing on both groups
// In this case i would like to get only the first group (the chapter number)

PS:我的英语会很差,但要先感谢

1 个答案:

答案 0 :(得分:0)

您可以使用第二组为可选的模式:

Chapter\s?([^:]+)(?::\s*(.*))?

Demo

您更新的代码:

string pattern = @"Chapter\s?([^:]+)(?::\s*(.*))?";
var m = Regex.Match(input, pattern);
相关问题