保留字符串中的所有反斜杠 [英] Preserve all backslashes in a string

查看:489
本文介绍了保留字符串中的所有反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含反斜杠的字符串:

I have a string containing backslashes:

"{ \time 4/4 \key c \major d'4 }"

当我尝试在nodejs child_process中传递它或只是在console.log中传递它,
反斜杠被移除:

When I try to pass it in a nodejs child_process or just to console.log it, the backslashes are removed:

console.log("{ \time 4/4 \key c \major d'4 }");   
// "{   ime 4/4 key c major d'4 }"

I我已经尝试了所有可以找到的东西,比如 .replace(/ \\ / g,'\\') JSON。 stringify ,但似乎没有任何效果。

I have tried all things I cound find, such as .replace(/\\/g, '\\') or JSON.stringify, but nothing seems to work.

字符串是动态构造的,所以我无法手动转义它。

The string is constructed dynamically so I can't escape it manually.

任何想法?

评论后更新:

我从用python编写的库中获取此字符串( python-mingus )使用 node-python

I am getting this string from a library written in python (python-mingus) using node-python.

据我从答案和评论中理解,没有办法正确解析字符串而不改变库或包装器......

As I understand from the answers and the comments, there is no way to parse the string correctly without altering either the library or the wrapper...

谢谢大家。

推荐答案

不,你的字符串不包含(字面值)反斜杠。

No, your string does not contain (literal) backslashes.

\ 是一个转义字符, \t \ k \ m 在解析时被视为转义序列 (而不是在打印时,如您所想) 。它们甚至从未到达替换,因为它们在运行时不再存在。此外,对于无法识别的序列( \k \m ),只会忽略反斜杠。

\ is an escape character, and \t, \k and \m are treated as escape sequences at the time of parsing (and not at the time of printing, as you seem to think). They never even reach your replace because they aren't there anymore when it runs. Also, for unrecognised sequences (\k and \m), the backslash is simply ignored.

防止这种情况的唯一方法是在源代码中添加额外的反斜杠

The only way to prevent that is to add an additional backslash in the source code:

"{ \\time 4/4 \\key c \\major d'4 }"

这篇关于保留字符串中的所有反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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