如何用C#正则捕获含内部双引号的跨行引号内文本
C#正则捕获含双写引号的跨多行文本
问题描述
我有如下文本:
This part is not import. He said : "I told him: ""Hi"", but he ignored me. I thought ""Why?"", but that is not my business. This is the end" This also is not important and should not be captured.
需要实现:捕获单个双引号包裹的所有文本,忽略其中的双写引号(""),且目标文本可跨3行及以上。期望捕获结果:
I told him: ""Hi"", but he ignored me. I thought ""Why?"", but that is not my business. This is the end
我尝试了多个正则表达式,但要么匹配空文本,要么错误捕获内部的双写引号,无法实现需求。
解决方案
在C#中,可以通过匹配"非结束单个引号"的逻辑来实现,推荐使用以下正则:
var regex = new Regex(@"(?<=^|.)""((?>[^"""]|""""|[\r\n])*?)""", RegexOptions.Singleline);
正则逻辑解释
(?<=^|.)"":正向预查,确保匹配的是单个双引号(避免把双写引号的其中一半当作起始引号)(?>[^"""]|""""|[\r\n])*?:原子组(避免回溯问题),匹配三种内容:[^"""]:任何非双引号的字符"""":双写的引号(作为整体匹配,不会被误判为结束引号)[\r\n]:换行符(支持跨多行文本)
*?:非贪婪匹配,确保遇到第一个单个双引号时就停止匹配"":匹配结束的单个双引号
完整代码示例
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = @"This part is not import. He said : ""I told him: """"Hi"""", but he ignored me. I thought """"Why?"""", but that is not my business. This is the end"" This also is not important and should not be captured."; var regex = new Regex(@"(?<=^|.)""((?>[^"""]|""""|[\r\n])*?)""", RegexOptions.Singleline); Match match = regex.Match(input); if (match.Success) { Console.WriteLine("捕获到的内容:"); Console.WriteLine(match.Groups[1].Value); } else { Console.WriteLine("未匹配到目标内容"); } } }
运行这段代码,会输出你期望的捕获文本。
内容的提问来源于stack exchange,提问作者Ahmad
相关产品推荐
相关产品推荐

