如何使用函数式方法处理正则表达式?目前我希望用户输入一个输入,即使他们以大写字母输入,它仍然会给出响应?我不确定如何实现这一点。
open System
open System.Drawing
open System.Windows.Forms
let (|Hello|Bye|None|) input =
match input with
| "hello" | "hi" | "morning"
-> Hello
| "Goodbye" | "bye" | "go"
-> Bye
| _
-> None
let rand = new Random()
let hello_response () =
let n = rand.Next(10)
match n with
| 0 -> "How do you do."
| 1 -> "Is nice talking to you."
| 2 -> "Tell me something new."
| 3 -> "Nice to meet you."
| 4 -> "My pleasure."
| 5 -> "Hi."
| 6 -> "Hello."
| 7 -> "Good day."
| 8 -> "Salutation!"
| 9 -> "Welcome!"
let good_bye_response () =
let n = rand.Next(10)
match n with
| 0 -> "Talk to you soon."
| 1 -> "It was nice talking to you."
| 2 -> "Good bye."
| 3 -> "Stay a bit longer."
| 4 -> "Adios amigo."
| 5 -> "Bye."
| 6 -> "Adios."
| 7 -> "See you."
| 8 -> "Please don't go"
| 9 -> "Why are you leaving me alone?"
let none_response (str:string) =
let n = rand.Next(10)
match n with
| 0 -> "Maybe."
| 1 -> "Perhaps " + str
| 2 -> "Yes."
| 3 -> "Ah!"
| 4 -> "Whatever."
| 5 -> "Sorry, the chat closed unexpectedly. What was your last
question?"
| 6 -> "Where were we? I losed track of the conversation."
| 7 -> "Very interesting"
| 8 -> "Wow!"
| 9 -> "Mmmmmm!"
let rec response (token: string) (str: string) =
match token with
| Hello
-> hello_response ()
| Bye
-> good_bye_response ()
| ""
-> none_response str
| None when (str.IndexOf(" ") > 0)
-> response (str.Substring(0,str.IndexOf(" ")))
(str.Substring(str.IndexOf(" ")+1))
| None when (str.IndexOf(" ") < 0)
-> response str ""
| None
-> str
let marketbot_resp (str: string) =
if (str.IndexOf(" ") > 0) then
response (str.Substring(0,str.IndexOf(" ")))
(str.Substring(str.IndexOf(" ")+1)) + "\n"
else
response str "" + "\n"
您可以在 F# 中使用正则表达式,就像在 C# 或 VB.NET(或任何其他 .NET 语言)中使用正则表达式一样。 MSDN 提供了有关该主题的相当广泛的文档。 检查一下。
根类是
System.Text.RegularExpressions.Regex
。最简单的匹配方法是通过 IsMatch
静态方法:
let (|Hello|Bye|None|) input =
if Regex.IsMatch( input, "(?i)hello|hi|morning" ) then Hello
elif Regex.IsMatch( input, "(?i)goodbye|bye|go" ) then Bye
else None
您还可以通过创建
Regex
的实例并重用它来“缓存”正则表达式。这将为您节省一点点性能:
let (|Hello|Bye|None|) =
let hello = Regex "(?i)hello|hi|morning"
let bye = Regex "(?i)goodbye|bye|go"
fun input ->
if hello.IsMatch input then Hello
elif bye.IsMatch input then Bye
else None
但是,对于这个特定的任务,我认为正则表达式有点矫枉过正。我只是在匹配之前将字符串转换为小写:
let (|Hello|Bye|None|) (input: string) =
match input.ToLower() with
| "hello" | "hi" | "morning"
-> Hello
| "goodbye" | "bye" | "go"
-> Bye
| _
-> None