Regex Str.global替换为OCaml,将克拉放在不应该放的地方';不可能
我正在努力将多行字符串转换成一个标记列表,这对我来说可能更容易使用 根据我的项目的具体需要,我将在输入中出现的任何克拉符号中填充空格,以便将Regex Str.global替换为OCaml,将克拉放在不应该放的地方';不可能,regex,string,ocaml,Regex,String,Ocaml,我正在努力将多行字符串转换成一个标记列表,这对我来说可能更容易使用 根据我的项目的具体需要,我将在输入中出现的任何克拉符号中填充空格,以便将“^”转换为“^”。我正在使用类似于以下函数的函数来执行此操作: let bad_function string = Str.global_replace (Str.regexp "^") " ^ " (string) 然后我使用下面的函数将这个多行字符串转换成一个标记列表(忽略空格) 出于某种原因,bad_函数会在不应该的地方添加克拉。以下面的代码行为例
“^”
转换为“^”
。我正在使用类似于以下函数的函数来执行此操作:
let bad_function string = Str.global_replace (Str.regexp "^") " ^ " (string)
然后我使用下面的函数将这个多行字符串转换成一个标记列表(忽略空格)
出于某种原因,bad_函数
会在不应该的地方添加克拉。以下面的代码行为例:
(bad_function " This is some
multiline input
with newline characters
and tabs. When I convert this string
into a list of tokens I get ^s showing up where
they shouldn't. ")
字符串的第一行变成:
^ This is some \n ^
当我将bad_函数
的输出输入string_to_令牌
时,我得到以下列表:
string_to_tokens (bad_function " This is some
multiline input
with newline characters
and tabs. When I convert this string
into a list of tokens I get ^s showing up where
they shouldn't. ")
["^"; "This"; "is"; "some"; "^"; "multiline"; "input"; "^"; "with";
"newline"; "characters"; "^"; "and"; "tabs."; "When"; "I"; "convert";
"this"; "string"; "^"; "into"; "a"; "list"; "of"; "tokens"; "I"; "get";
"^s"; "showing"; "up"; "where"; "^"; "they"; "shouldn't."]
为什么会发生这种情况,我如何修复这些函数,使它们的行为符合我的要求?如模块中所述
^在行首匹配:在
匹配的字符串,或正好在“\n”字符之后
因此,必须使用转义字符“\”引用“^”字符。
但是,请注意(也来自文档)
正则表达式中的任何反斜杠字符都必须加倍为
通过OCaml字符串解析器
这意味着你必须在没有得到警告的情况下,用一个双“\”来做你想做的事情
这应该可以做到:
let bad_function string = Str.global_replace (Str.regexp "\\^") " ^ " (string);;
let bad_function string = Str.global_replace (Str.regexp "\\^") " ^ " (string);;