模式匹配“字符串”以获得Escaped报价(Pattern Matching on 'String' to get Escaped Quote)

编程入门 行业动态 更新时间:2024-10-23 23:28:33
模式匹配“字符串”以获得Escaped报价(Pattern Matching on 'String' to get Escaped Quote)

是否可以在转义报价上进行模式匹配?

这是我(错误地)尝试的:

g :: String -> Bool g ('\\':'"':_) = True g _ = False

但结果不符合我期望的功能行为。

ghci> g "\"" False ghci> g "\\\"" True

Is it possible to pattern match on an escaped quote?

Here's what I (incorrectly) tried:

g :: String -> Bool g ('\\':'"':_) = True g _ = False

But the results don't meet my desired function behavior.

ghci> g "\"" False ghci> g "\\\"" True

最满意答案

字符串字符串之间有区别。 基本上,一个字符串是一个接一个的字符列表,字符串文字只是一些符号 。 该符号必须“逃避”某些字符,否则会导致模糊的语法,但它仍然表示没有转义的字符串。

Haskell表达式"\""是包含单个字符的字符串的表示法 " 。 我们需要反斜杠,因为在没有它的情况下编写"""会使字符串的内容看起来就像一个结束引号并打破我们的符号。但字符串本身仍然只有一个" 。

当您匹配字符串值时,您将匹配字符串本身,而不是其符号。 这意味着您不必担心字符串中的转义字符,因为它们只存在于符号级别。 所以要匹配只包含"你会使用以下模式的字符串:

foo ['"'] = ...

如果您尝试考虑反斜杠,则会匹配不同的字符串。

There's a difference between a string and a string literal. Basically, a string is a list of characters one after the other and a string literal is just some notation for the same. The notation has to "escape" certain characters because it would otherwise lead to ambiguous syntax, but it still expresses the string without the escaping.

The Haskell expression "\"" is notation for the string containing a single character ". We need the backslash because writing """ without it would make the contents of the string look just like a closing quote and break our notation. But the string itself still only has a ".

When you're matching on a string value, you're matching on the string itself, not its notation. This means that you do not have to worry about escape characters in the string, because those only exist at the level of notation. So to match the string containing just " you would use the following pattern:

foo ['"'] = ...

If you tried to account for a backslash, you would be matching a different string.

更多推荐

本文发布于:2023-04-27 15:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327155.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   模式   Escaped   Pattern   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!