string - Common Lisp 的 FORMAT 有反义词吗?

标签 string lisp common-lisp string-parsing

我有一个问题困扰了我一段时间。 Common Lisp format 函数是否可逆(至少在某种程度上),因为格式字符串可用于从 format 的输出中检索原始参数?我知道映射不是一对一的(一个例子是 ~@:(~a~) 将输入转换为大写并且不可逆),所以必然会丢失一些信息.我真正想到的是用于字符串解析的正则表达式的替代方法。例如,我希望能够写:

(destructure-format t "[~{~a~^, ~}]" "[0, 1, 2]")

并得到响应:

=> (0 1 2)

您是否知道任何此类尝试或讨论类似方法的论文?

最佳答案

标准中没有内容

标准中没有这样的内容。 Format 表达式没有携带足够的信息来使它在任何实际意义上有用。对于几乎所有不绑定(bind)的东西 *print-readably* , 有一些方法很难回读输出。如果您给出了列表格式,

(destructure-format t "[~{~a~^, ~}]" "[0, 1, 2]")

任何解决方案都必须检查格式指令。那么它可以明确地观察到什么?字符串中的第一个字符必须是 #\[,最后一个字符必须是 #\]一些 >", "~a 生成的字符串中分隔输出。那么会出现什么模棱两可的情况呢?任何会导致在输出中写入 ", " 的内容。例如,

CL-USER> (format t "[~{~a~^, ~}]" '(|, | 2 3))
[, , 2, 3]
NIL
CL-USER> (format t "[~{~a~^, ~}]" '(|, | | ,|))
[, ,  ,]
NIL
CL-USER> (format t "[~{~a~^, ~}]" '(|, | | ,| |,|))
[, ,  ,, ,]
NIL
CL-USER> (format t "[~{~a~^, ~}]" '(|, | | ,| #\,))
[, ,  ,, ,]
NIL

第三方库

虽然库推荐在 Stack Overflow 上是题外话,但这个问题并不是一开始就提出来的,而是在看到 Rörd's answer 之后建议使用外部函数调用 C 的 scanf,我很快在 CLiki 上搜索 scanf 并找到了 format-setf (重新阅读评论,我看到 Xach found it first ),其描述如下:

The Common Lisp equivalent of scanf().

A (relatively) frequently asked question on comp.lang.lisp is "What's the equivalent to scanf()?". The usual answer is "There isn't one, because it's too hard to work out what should happen". Which is fair enough.

However, one year Christophe was bored during exams, so he wrote format-setf.lisp, which may do what you want.

It should be pointed out that currently the behaviour of this program is unspecified, in more senses than just the clobbering of symbols in the "CL" package. What would be nice would be to see a specification appear for its behaviour, so that I don't have an excuse when people say that it's buggy.

其他选择

由于您最终真的会问“这可以匹配的可能方式是什么,您实际上是在要求正则表达式以及格式可能实现的额外内容。 p>

What I have in mind exactly is rather an alternative to regular expressions for string parsing.

如果您正在寻找正则表达式,那么正则表达式非常适合。如果您正在寻找不是正则表达式的解析,那么您可能想要编写一个真正的解析器。第一次可能会让人望而生畏,但之后就会变得容易得多,而 Common Lisp 让它变得相对轻松。甚至还有可用的解析器生成库。另一方面,如果您正在寻找序列化和反序列化,Common Lisp 阅读器和编写器使 s-expressions 成为一个不错且简单的选择。

关于string - Common Lisp 的 FORMAT 有反义词吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23489859/

相关文章:

c++ - C 标记化字符串

Racket 中的 Lambda 解释

lisp - Elisp中定义的pow-mod函数在哪里

LISP 更好理解多级列表

lisp - 通用 Lisp : getting an error using readtable-case

python - 将列表列表的数据从字符串格式转换为列表

C++ string() 与 c 字符串的比较。为什么这行得通?

c - 在使用系统调用生成的 printf 上输出两个字符串时遇到问题

lisp - 调用参数应为结构实例的函数

common-lisp - 在列表中加入字符串的规范方法是什么?