在双引号内转义双引号 [英] Escape double quotes within double quotes
问题描述
我有一个字符串[{"Id":"1","msg":""Lorem Ipsum""}]
,在其中我只需要对引号内的引号进行转义,例如[{"Id":"1","msg":"\"Lorem Ipsum\""}]
.我无权修改生成器代码,因此我正在寻找正则表达式解决方案或高效的Java解决方案.
I have a string [{"Id":"1","msg":""Lorem Ipsum""}]
in which I need to just escape the quotes inside the quotes like this [{"Id":"1","msg":"\"Lorem Ipsum\""}]
. I don't have access to generator code to modify, so I'm looking for a regex solution or efficient Java solution.
我尝试用\"[^\"]*?(\"*)[^\"]*?\"
选择匹配项,这没有用.任何帮助,我们真的很感激.预先感谢.
I tried selecting matches with \"[^\"]*?(\"*)[^\"]*?\"
which is of no use. Any help is really appreciated. Thanks in advance.
请注意,不能保证模式始终都是两个双引号,"Lorem "Ipsum" test"
也可能是这样,应该变成"Lorem \"Ipsum\" test"
.
Note that it isn't guaranteed that the pattern is always two double quotes together, it can be something like this too "Lorem "Ipsum" test"
, which should become "Lorem \"Ipsum\" test"
.
PS:我已经看过将正则表达式在双引号内转义双引号
推荐答案
问题
有限自动机-正则表达式的理论等效项-无法解析递归结构.由于您可以使用内部引号,也可以使用内部-内部引号,因此使用正则表达式无法解决您的问题.
The problem
A finite automaton - the theoretical equivalent of a regex - can't parse recursive structures. Since you can have inner quotes, and possible inner-inner quotes, your problem can't be solved using a regex.
尽管现代的正则表达式引擎可以通过几个扩展来解决此问题,但不要浪费时间寻找引号内的引号.您很快就会发现,您实际上是在构建一个完整的JSON解析器.
Although modern regex engines can overcome this problem with several extensions, don't waste your time on hunting quotes-within-quotes. You'll soon find out that you're actually building a full blown JSON parser.
如 @ johnchen902所述,即使是图灵机驱动的解析器也无法处理歧义-因此,最好不要尝试建议修复损坏的JSON.
As @johnchen902 stated, even a turing-machine powered parser can not handle ambiguities - so you better not try to suggest a fix to the broken JSON.
给定的字符串不是有效的JSON .它可能是使用字符串连接创建的,这通常是一个坏主意,因为它不能正确地转义.您应该使用可以从Java数据结构构建JSON的JSON库,例如 gson .创建一个对象列表,向其中添加一个对象到对象"字典,然后让该库进行转义和转换.
The given string is not a valid JSON. It's probably created using string concatenation, which is generally a bad idea because it does not escape correctly. You should use a JSON library that can build JSON from a Java data structure, like gson. Create a list of Objects, add an Object-to-Object dictionary to it, and let the library do the escaping and conversions.
如果您是从外部来源收到的String,则索取可以使用的 valid json是完全合法的.我想创建者将字符串缝合在一起,这是构建结构化语言的错误方法.要求原始创建者使用标准库来创建JSON,或者至少使用验证器.所有现代编程语言都提供了这些机制.
If you have received the String from an external source, it's perfectly legitimate to ask for a valid json you can work with. I guess that the creator stitched Strings together, which is the wrong way to build a structured language. Ask the original creator to use a standard library for creating JSONs, or at least use a validator. All modern programming languages offer these mechanisms.
这篇关于在双引号内转义双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!