【问题标题】:Regex: match quotations marks in C# [duplicate]正则表达式:匹配 C# 中的引号 [重复]
【发布时间】:2019-03-03 17:12:09
【问题描述】:

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

这是我的代码:

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

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

【问题讨论】:

  • 您的代码为我打印出"(双引号字符),而不是空字符串。 ["?] 表示 " OR ?,所以它匹配起始双引号。
  • @canton7 如何让它匹配任何引号和问号?
  • @TheThugger 这个应该可以工作\?\"(\?\")
  • @WaelAbbas 仍然无法解决问题。它只匹配引号一次。
  • 你必须遍历 Regex.Matches

标签: c# regex


【解决方案1】:

如果您想匹配问题所陈述的所有引号和问号,那么您的模式是可以的。问题是Regex.Match 只会返回它找到的 first 匹配项。来自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

我还要指出,如果您真的想匹配 所有 标点符号,包括“法语”引号(«»)、“智能”引号(@ 987654329@ 和 )、倒置问号 (¿) 等等,您可以将 Unicode Character categories\p{P} 之类的模式一起使用。

【讨论】:

    【解决方案2】:

    你需要调用 Matches 而不是 Match。

    例子:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      • 2015-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 2019-05-17
      相关资源
      最近更新 更多