有没有办法“匹配”以某个值开头的字符串?
Is there a way to `match` on a string that starts with some value?
例如,考虑以下表达式:
match string with
| "Foo " ^ rest -> rest
| "Bar " ^ rest -> rest
| _ -> "unmatched"
不幸的是,这是一个syntax error。有什么方法可以实现这种行为吗?
OCaml function parameter pattern matching for strings 中有一些关于为什么无法在模式匹配中解构字符串的解释。您只能匹配纯字符串。
相反,您可以使用提供正则表达式的新 String.starts_with
(OCaml 4.13) to compare the string with a fixed prefix, or use the Str
模块,或将字符串转换为列表并匹配该列表。
另一种可能性是拆分进入匹配的字符串,这样您就可以基于普通旧字符串的元组进行匹配。
String.(
match sub s 0 4, sub s 4 (length s - 4) with
| "foo ", rest -> ...
| "bar ", rest -> ...
| _ -> ...
)
如果您创建一个函数来根据一定数量的字符对字符串进行分区,这样看起来会更好看。
let part s n =
String.(sub s 0 n, sub s n (length s - n))
现在:
match part s 4 with
| "foo ", rest -> ...
| "bar ", rest -> ...
| _ -> ...
例如,考虑以下表达式:
match string with
| "Foo " ^ rest -> rest
| "Bar " ^ rest -> rest
| _ -> "unmatched"
不幸的是,这是一个syntax error。有什么方法可以实现这种行为吗?
OCaml function parameter pattern matching for strings 中有一些关于为什么无法在模式匹配中解构字符串的解释。您只能匹配纯字符串。
相反,您可以使用提供正则表达式的新 String.starts_with
(OCaml 4.13) to compare the string with a fixed prefix, or use the Str
模块,或将字符串转换为列表并匹配该列表。
另一种可能性是拆分进入匹配的字符串,这样您就可以基于普通旧字符串的元组进行匹配。
String.(
match sub s 0 4, sub s 4 (length s - 4) with
| "foo ", rest -> ...
| "bar ", rest -> ...
| _ -> ...
)
如果您创建一个函数来根据一定数量的字符对字符串进行分区,这样看起来会更好看。
let part s n =
String.(sub s 0 n, sub s n (length s - n))
现在:
match part s 4 with
| "foo ", rest -> ...
| "bar ", rest -> ...
| _ -> ...