简体   繁体   English

正则表达式:转义\\“ / \\\\” / g不起作用

[英]regex: escaping \“ /\\”/g Not Working

I have a string that goes something like this: 我有一个类似这样的字符串:

/* ACTUAL DATA */

\n\nsampleArr[0] = {
    \n\t\tid: '28375023',
    \n\t\ttelephoneNumber: 5558378402,
    \n\t\tage: \" 4 \",
    \n\t\tmessageID: '287592',
    \n\t\tcommentID: '23845702',
    \n\t\tfoobar: 'foobar' \n\t
};

I am able to remove all \\n\\t\\t using regex but just cannot deal with age section where it has \\" 4 \\". 我可以使用正则表达式删除所有\\ n \\ t \\ t,但不能处理年龄段中有“ 4”的部分。

 const input = String.raw`{ name: 'foo', age: 12, address: \\"1212 Mason st. \\", zipcode: '12345', state: \\"CA\\" }`; console.log(input.replace(/\\\\"/g, "'")); 

My main goal is to turn this into an object. 我的主要目标是将其变成一个对象。 However, the escaped characters \\" are creating some major issues. I tried to use str.replace(/\\\\"/g, "'") and it seems like it is not matching nor replacing it. 但是,转义的字符\\“造成了一些重大问题。我尝试使用str.replace(/\\\\"/g, "'") ,看来它既不匹配也不替换它。 However, on https://regex101.com , it definitely is selecting all \\" s. Any suggestions? 但是,在https://regex101.com上 ,它肯定是选择所有\\“。有什么建议吗?

Assuming the backslashes escaping the double quotation marks in your input are physical backslashes, then your replacement should work, so something else must be going on. 假设在输入中转义双引号的反斜杠是物理反斜杠,那么您的替换应该可以工作,因此还必须进行其他操作。

 const input = String.raw`{ name: 'foo', age: 12, address: \\"1212 Mason st. \\", zipcode: '12345', state: \\"CA\\" }`; console.log(input.replace(/\\\\"/g, "'")); 

In the above, we use template strings to specify multi-line input, and String.raw to avoid interpreting the \\" escapes (just as a handy way of providing the input string). 在上面,我们使用模板字符串指定多行输入,并使用String.raw避免解释\\"转义符(作为提供输入字符串的便捷方法)。

Note that this will fail if the strings themselves contain escaped quotation marks, as in 请注意,如果字符串本身包含转义的引号,则此操作将失败,例如

address: \"685 9th \"A\" Main Rd.\",

The ultimate solution is to have the back-end or whoever is producing these strings not escape the double quotation marks unless they occur within the strings. 最终的解决方案是让后端或产生这些字符串的人不要逃脱双引号,除非它们出现字符串中。 In other words, produce proper JSON. 换句话说,产生适当的JSON。

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

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