C#正则表达式替换每行中双引号的第一个和最后一个出现 [英] C# Regex replace the first and last occurrence of double quote in each line

查看:41
本文介绍了C#正则表达式替换每行中双引号的第一个和最后一个出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个多行字符串,带有不转义的双引号,可以防止对该字符串进行解析.

There is a multi-line string with unescaped double quotes that prevents the string from being parsed.

字符串示例:

ns:common.topic.description"1942年:电影《爱情故事》,1994年7月15日在Vidhu Vinod Chopra sorti上出售.杰基·史洛夫(Jackie Shroff).ns:common.topic.description"1942:电影Bollywoodzki的爱情故事mi \ u0142osny i电影akcji zrealizowany w 1993 roku przez Vidhu Vinod Chopra,autora takich电影\ u00f3w jak Misja w Kaszmirze,czy Eklavya:皇家卫队.Wrololg \ u0142 \ u00f3wnych Anil Kapoor i Manisha Koirala',w drugoplanowych Jackie Shroff,Anupam Kher,Danny Denzongpa i Pran.电影由\ u0142 hitem jako音乐剧.Premierajego odby \ u0142a si \ u0119 ju \ u017go popoweterana Bollywoodu Rahul Dev Burman.致历史记录mi \ u0142osna.Jej t \ u0142em jest rok 1942,w kt \ u00f3rym Gandhi has \ u0142em"Quit India!" wezwa \ u0142 Anglik \ u00f3w do odejj \ u015bcia z kraju po-200Syn s \ u0142u \ u017c \ u0105cego Anglikom Indusa zakochuje si \ u0119 wc \ u00f3rce bojownika o wolno \ u015b \ u0107 kraju."@ pl;

我已经尝试过使用此代码替换字符串的每一行中第一次出现和最后出现的"(该代码是错误的,无法正常工作,只是不知道其他方式做所需的事情):

I've tried this code to replace the first and the last occurrence of " on each line of the string (the code is bad and doesn't work, just don't know other way to do what is needed):

var freebaseFixedRdfString = Regex.Replace(freebaseFixedRdfString,"\",委托(匹配){bool first = match.Index == 1;bool last = match.NextMatch().Index == 0;如果(第一个||最后一个)返回 "\"\"\"";别的返回match.Value;},RegexOptions.Compiled |RegexOptions.Multiline);

如何使用正则表达式替换要替换为""的第一个和最后一个" 吗?

How to use regex to replace the first and the last " to be replaced with """ ?

推荐答案

如果要替换开头或最后一个位置的引号,则不需要正则表达式.但是,在您的示例中,引号不在文本行的开头或结尾.

If you want to replace the quote in the initial or the last position, you do not need regex. However, in your example the quotes are not in the initial or the last position on the line of text.

这是您可以执行的操作:

Here is how you can do this:

var res = Regex.Replace(text, "(?<=^[^\"]*)\"|\"(?=[^\"]*$)", "\"\"\"");

正则表达式使用先行和后行构造来替换引号

The regex uses lookahead and lookbehind constructs to replaces a quote when

  • 行首与该引号之间没有其他引号,或者
  • 这一行和行尾之间没有其他引号.

演示.

var text = "Quick \"brown fox jumps \"over\" the lazy\" dog";
var res = Regex.Replace(text, "(?<=^[^\"]*)\"|\"(?=[^\"]*$)", "\"\"\"");

转换

Quick "brown fox jumps "over" the lazy" dog

Quick """brown fox jumps "over" the lazy""" dog

这篇关于C#正则表达式替换每行中双引号的第一个和最后一个出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆