繁体   English   中英

正则表达式仅删除两次出现的字符串

[英]Regular expression to delete only two occurrences of a string

我有以下字符串

"{\"title\": \"Option 1\", \"description\": \"This is the \"FIRST OPTION\" in the list.\"}"

我需要用&符替换FIRST OPTION周围的转义引号。 这样看起来像这样:

"{\"title\": \"Option 1\", \"description\": \"This is the "FIRST OPTION" in the list.\"}"

我能想到的唯一方法是更改\\“ description \\”:\\“之后的两个\\”出现(必须只有两个,因为在字符串的结尾附近有转义的引号需要像这样保留)我无法弄清楚语法(我对正则表达式非常陌生)。

有没有一种方法可以在JS中使用正则表达式来实现?

更新:忘记提及FIRST OPTION只是一个示例,它可以是任何字符串,我需要删除其周围的转义引号。

查找/\\\\"(?=FIRST OPTION)|(FIRST OPTION)\\\\"/
替换$1"

https://regex101.com/r/Nwnr13/2


或者,如果要求第一个选项都具有两个转义引号,则此

查找/\\\\"(FIRST OPTION)\\\\"/
替换"$1"

https://regex101.com/r/tp9I5T/2

请参见以下示例:

 var text="{\\"title\\": \\"Option 1\\", \\"description\\": \\"This is the \\"FIRST OPTION\\" in the list.\\"}"; text=text.replace(/([\\{|:|,])(?:[\\s]*)(")/g, "$1'") .replace(/(?:[\\s]*)(?:")([\\}|,|:])/g, "'$1") .replace(/["]/gi, '"').replace(/[']/gi, '"'); text=JSON.stringify(text); console.log(text); text=JSON.parse(text); console.log(text); 

从您的JSON字符串开始,最简单的理解是,最安全的事情是将其转换回Javascript对象,仅对description字段进行操作,然后将其转换回String。
JSON.parse()和JSON.stringify()会做到这一点。
(如@jdubjdub所建议,但未写出,所以我去了)

您将此作为您的字符串:

"{\"title\": \"Option 1\", \"description\": \"This is the \"FIRST OPTION\" in the list.\"}"

出于我们的测试目的,要将其分配给变量,需要额外的转义:

var yourstring = "{\"title\": \"Option 1\", \"description\": \"This is the \\\"FIRST OPTION\\\" in the list.\"}";

然后,您将var obj = JSON.parse(yourstring)制成一个对象,您将仅对obj.description进行操作以替换引号,然后您将var changedstring = JSON.stringify(obj)以一个字符串结尾再次。

 var yourstring = "{\\"title\\": \\"Option 1\\", \\"description\\": \\"This is the \\\\\\"FIRST OPTION\\\\\\" in the list.\\"}"; console.log('Original String:'); console.log(yourstring); var obj = JSON.parse(yourstring); console.log('String parsed into an Object:'); console.log(obj); var newdesc = obj.description.replace(/"/g, '"'); obj.description = newdesc; console.log('Modified Object:'); console.log(obj); var newstring = JSON.stringify(obj); console.log('New String:'); console.log(newstring); 

暂无
暂无

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

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