Haskell 无法识别字符 类 的 Perl 兼容正则表达式
Perl compatible regular expressions with character classes not recognized in Haskell
我希望在 Haskell 中使用 perl 兼容的正则表达式,特别是简写字符 类 \w
和 \s
等
我了解这些在标准 posix 模块中不可用:
import Text.Regex.Posix
"this is a string" =~ "\S+"
<interactive>:3:25: error:
lexical error in string/character literal at character 'S'
然而,我希望 pcre 包能够处理这个问题,但看到了相同的结果:
import Text.Regex.PCRE
"this is a string" =~ "\S+"
<interactive>:2:25: error:
lexical error in string/character literal at character 'S'
在 python 中,它会像这样工作:
>>> import re
>>> re.findall(r'\S+', "this is a string")
['this', 'is', 'a', 'string']
如何在 Haskell 中使用这些正则表达式字符 类?
这与正则表达式或 Haskell 与 Python 无关。请注意,您也不会写 re.findall("\S+", "this is a string")
†。您需要 原始字符串文字 才能像这样使用反斜杠。 Haskell 没有内置原始字符串文字,但它确实有准引号,允许您 emulate them.
Prelude> :set -XQuasiQuotes
Prelude> :m +Text.RawString.QQ Text.Regex.PCRE
Prelude Text.RawString.QQ Text.Regex.PCRE> "this is a string" =~ [r|\S+|] :: String
"this"
或者,只需对反斜杠进行两次转义:"this is a string" =~ "\S+"
†实际上单反斜杠版本在 Python 中有效,即使使用简单的引号,但这似乎是一个后备方案规则。最好不要依赖这个。
有了 Posix,您可以使用:
\w ... [\p{L}\p{M}\p{Nd}\p{Nl}\p{Pc}]
\W ... [\p{L}\p{M}\p{Nd}\p{Nl}\p{Pc}]
\s ... [[:space:]]
\S ... [^[:space:]]
\d ... [[:digit:]]
\D ... [^[:digit:]]
使用 PCRE 包您可以使用:
\w ... [\p{L}\p{M}\p{Nl}\p{Nd}\p{Pc}]
\W ... [^\p{L}\p{M}\p{Nl}\p{Nd}\p{Pc}]
\s ... [\p{Z}\t\n\cK\f\r\x85]
\S ... [^\p{Z}\t\n\cK\f\r\x85]
\d ... \p{Nd}
\D ... \P{Nd}
我希望在 Haskell 中使用 perl 兼容的正则表达式,特别是简写字符 类 \w
和 \s
等
我了解这些在标准 posix 模块中不可用:
import Text.Regex.Posix
"this is a string" =~ "\S+"
<interactive>:3:25: error:
lexical error in string/character literal at character 'S'
然而,我希望 pcre 包能够处理这个问题,但看到了相同的结果:
import Text.Regex.PCRE
"this is a string" =~ "\S+"
<interactive>:2:25: error:
lexical error in string/character literal at character 'S'
在 python 中,它会像这样工作:
>>> import re
>>> re.findall(r'\S+', "this is a string")
['this', 'is', 'a', 'string']
如何在 Haskell 中使用这些正则表达式字符 类?
这与正则表达式或 Haskell 与 Python 无关。请注意,您也不会写 re.findall("\S+", "this is a string")
†。您需要 原始字符串文字 才能像这样使用反斜杠。 Haskell 没有内置原始字符串文字,但它确实有准引号,允许您 emulate them.
Prelude> :set -XQuasiQuotes
Prelude> :m +Text.RawString.QQ Text.Regex.PCRE
Prelude Text.RawString.QQ Text.Regex.PCRE> "this is a string" =~ [r|\S+|] :: String
"this"
或者,只需对反斜杠进行两次转义:"this is a string" =~ "\S+"
†实际上单反斜杠版本在 Python 中有效,即使使用简单的引号,但这似乎是一个后备方案规则。最好不要依赖这个。
有了 Posix,您可以使用:
\w ... [\p{L}\p{M}\p{Nd}\p{Nl}\p{Pc}]
\W ... [\p{L}\p{M}\p{Nd}\p{Nl}\p{Pc}]
\s ... [[:space:]]
\S ... [^[:space:]]
\d ... [[:digit:]]
\D ... [^[:digit:]]
使用 PCRE 包您可以使用:
\w ... [\p{L}\p{M}\p{Nl}\p{Nd}\p{Pc}]
\W ... [^\p{L}\p{M}\p{Nl}\p{Nd}\p{Pc}]
\s ... [\p{Z}\t\n\cK\f\r\x85]
\S ... [^\p{Z}\t\n\cK\f\r\x85]
\d ... \p{Nd}
\D ... \P{Nd}