繁体   English   中英

使用正则表达式将带引号的字符串与嵌入的非转义引号匹配

[英]Using Regex to match quoted string with embedded, non-escaped quotes

我正在尝试使用正则表达式匹配以下模式中的字符串。

string text = "'Emma','The Last Leaf','Gulliver's travels'";
string pattern = @"'(.*?)',?";

foreach (Match match in Regex.Matches(text,pattern,RegexOptions.IgnoreCase))
 {
    Console.WriteLine(match + " " + match.Index);
    Console.WriteLine(match.Groups[1].Captures[0]);
 }

这正确匹配了“ Emma”和“ The Last Leaf”,但是第三个匹配是“ Gulliver”。 但是理想的比赛是“格列佛游记”。 如何为这样的模式构建正则表达式?

由于,是分隔符,因此您可以尝试更改模式。 它应该工作。

string pattern = @"'(.*?)'(?:,|$)"; 

它的工作方式是,查找单引号,后跟逗号或行尾。

我认为这可以将'(.*?)',|'(.*)'作为正则表达式使用。

您可以考虑使用向后看/向前看:

 "(?<=^'|',').*?(?='$|',')"

用grep测试

kent$  echo "'Emma','The Last Leaf','Gulliver's travels'"|grep -Po "(?<=^'|',').*?(?='$|',')"
Emma
The Last Leaf
Gulliver's travels

如果您有单引号分隔的字符串,而Gulliver's包含一个不转义的单引号,则无法将其与字符串末尾区分开。 您总是可以用逗号将其分开,并从任一边修剪' ,但是我不确定那是您想要的:

string text = "'Emma','The Last Leaf','Gulliver's travels'";

foreach(string s in text.split(new char[] {','})) {
    Console.WriteLine(s.Trim('\''));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM