正则表达式:在C#中匹配引号[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我是正则表达式的新手,我似乎并没有找到这些模式的出路。我试图在句子(引号和问号)中匹配标点符号,但没有成功。

这是我的代码:

string sentence = "\"This is the end?\"";
string punctuation = Regex.Match(sentence, "[\"?]").Value;

我在这做错了什么?我希望控制台显示"?",但是,它显示了双引号。

c# regex
2个回答
3
投票

如果您想在问题中列出所有引号和问号,那么您的模式就可以了。问题是Regex.Match只返回它找到的第一场比赛。来自MSDN

在输入字符串中搜索指定正则表达式的第一次出现...

你可能想用Matches

string sentence = "\"This is the end?\"";
MatchCollection allPunctuation = Regex.Matches(sentence, "[\"?]");

foreach(Match punctuation in allPunctuation)
{
    Console.WriteLine("Found {0} at position {1}", punctuation.Value, punctuation.Index);
}

这将返回:

Found " at position 0
Found ? at position 16
Found " at position 17

我还要指出,如果你真的想匹配所有标点字符,包括'法语'引号(«»),'智能'引号(),倒置问号(¿)等等,你可以使用像Unicode Character categories这样的模式的\p{P}


2
投票

您需要调用匹配而不是匹配。

例:

string sentence = "\"This is the end?\"";
var matches = Regex.Matches(sentence, "[\"?]");
var punctuationLocations = string.Empty;
foreach(Match match in matches)
{
    punctuationLocations += match.Value + " at index:" + match.Index + Environment.NewLine;
}

// punctuationLocations:
//   " at index:0
//   ? at index:16
//   " at index:17
© www.soinside.com 2019 - 2024. All rights reserved.