如何在多行上拆分字符串并在 YAML 中保留空格? [英] How to break a string over multiple lines and preserve spaces in YAML?

查看:41
本文介绍了如何在多行上拆分字符串并在 YAML 中保留空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,这个问题类似于 这个,但仍然不同,所以这些答案不能解决我的问题:

Please note, that the question is similar like this one, but still different so that those answers won't solve my problem:

  • 用于插入控制字符,例如\x08,看来我得用双引号".
  • 所有空格都需要完全按照给定的方式保留.对于换行符,我明确使用 \n.
  • For insertion of control characters like e.g. \x08, it seems that I have to use double quotes ".
  • All spaces needs to be preserved exactly as given. For line breaks I use explicitly \n.

我有一些字符串数据需要存储在 YAML 中,例如:

I have some string data which I need to store in YAML, e.g.:

  • " 这是我相当长的字符串数据 "
  • 这是我很长的字符串数据"
  • This_is_my_quite_long_string_data"
  • Sting 数据\n其中\x08 包含控制字符"

并在 YAML 中需要它,如下所示:

and need it in YAML as something like this:

Key: "  This  is  my" +
     "  quite  long " +
     " string  data  "

这个只要单行就没有问题,但是不知道怎么把字符串内容放到多行.

This is no problem as long as I stay on a single line, but I don't know how to put the string content to multiple lines.

YAML 块标量样式 (>, |) 在这里无济于事,因为它们不允许转义,甚至会进行一些空格剥离、换行/空间替换对我的情况没用.

YAML block scalar styles (>, |) won't help here, because they don't allow escaping and they even do some whitespace stripping, newline / space substitution which is useless for my case.

看起来唯一的方法似乎是使用双引号 " 和反斜杠 \,如下所示:

Looks that the only way seems to be using double quoting " and backslashes \, like this:

Key: "\
  This is \
  my quite \
  long string data\
  "

YAML 在线解析器 中尝试这个结果 "这是我的很长字符串数据" 符合预期.

Trying this in YAML online parser results in "This is my quite long string data" as expected.

但不幸的是,如果子行"之一有前导空格,它会失败,如下所示:

But it unfortunately fail if one of the "sub-lines" has leading space, like this:

Key: "\
  This is \
  my quite\
   long st\
  ring data\
  "

这导致这是我的很长的字符串数据",删除了这个例子中quitelong这两个词之间的空格.我想到的唯一解决方法是用 \x20 替换每个子行的第一个前导空格,如下所示:

This results in "This is my quitelong string data", removed the space between the words quite and long of this example. The only thing that comes to my mind to solve that, is to replace the first leading space of each sub-line by \x20 like this:

Key: "\
  This is \
  my quite\
  \x20long st\
  ring data\
  "

因为我选择了 YAML 以获得最佳的人类可读格式,所以我发现 \x20 有点丑陋的解决方案.也许有人知道更好的方法?

As I'd chosen YAML to have a best possible human readable format, I find that \x20 a bit ugly solution. Maybe someone know a better approach?

为了保持人类可读性,我也不想为此使用 !!binary.

For keeping human readable, I also don't want to use !!binary for this.

推荐答案

代替 \x20,您可以简单地转义行中的第一个非缩进空格:

Instead of \x20, you can simply escape the first non-indentation space on the line:

Key: "\
  This is \
  my quite\
  \ long st\
  ring data\
  "

这适用于多个空格,您只需要转义第一个.

This works with multiple spaces, you only need to escape the first one.

这篇关于如何在多行上拆分字符串并在 YAML 中保留空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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