“{{”上的 ocaml 正则表达式问题
ocaml regex issue on "{{"
我正在尝试匹配字符串中的“{{”:
let regexp = Str.regexp_string "{{"
let _ = if Str.string_match regexp "a{{hello}}" 0
then print_string "yes"
else print_string "no"
这会打印 "no".
为什么这不匹配? “{”不是特殊字符:$^.*+?[]
除非我没有正确阅读手册,否则 string_match 应该会找到满足正则表达式的 s 的任何子字符串。
您应该改用 Str.search_forward
。
根据 ocaml docs:
string_match r s start tests whether a substring of s that starts at
position start matches the regular expression r.
我猜这意味着它不会像 search_forward
那样遍历整个字符串。
阅读 documentation 后,您正在使用的函数 string_match
会尝试匹配完整的字符串,因此您应该使用:
let regexp = Str.regexp_string ".*{{.*"
let _ = if Str.string_match regexp "a{{hello}}" 0
then print_string "yes"
else print_string "no"
#load "str.cma" ;;
string_match: Check if a string matches a regular expression
但是,我认为您可能会发现使用 search_forward
很有用,它实际上会在您的字符串中搜索模式
let re = Str.regexp "{{" in
try let _ = Str.search_forward re "a{{hello}}" 0 in
print_string "ok"
with _ -> ()
search_forward: Check if a string contains a match to a regular expression
我正在尝试匹配字符串中的“{{”:
let regexp = Str.regexp_string "{{"
let _ = if Str.string_match regexp "a{{hello}}" 0
then print_string "yes"
else print_string "no"
这会打印 "no".
为什么这不匹配? “{”不是特殊字符:$^.*+?[]
除非我没有正确阅读手册,否则 string_match 应该会找到满足正则表达式的 s 的任何子字符串。
您应该改用 Str.search_forward
。
根据 ocaml docs:
string_match r s start tests whether a substring of s that starts at position start matches the regular expression r.
我猜这意味着它不会像 search_forward
那样遍历整个字符串。
阅读 documentation 后,您正在使用的函数 string_match
会尝试匹配完整的字符串,因此您应该使用:
let regexp = Str.regexp_string ".*{{.*"
let _ = if Str.string_match regexp "a{{hello}}" 0
then print_string "yes"
else print_string "no"
#load "str.cma" ;;
string_match: Check if a string matches a regular expression
但是,我认为您可能会发现使用 search_forward
很有用,它实际上会在您的字符串中搜索模式
let re = Str.regexp "{{" in
try let _ = Str.search_forward re "a{{hello}}" 0 in
print_string "ok"
with _ -> ()
search_forward: Check if a string contains a match to a regular expression