我在F#中编写了以下代码:
let regexSymbol = new Regex(@"\b\}|\.\b")
if (Regex.IsMatch(".", regexSymbol.ToString())) then
printfn "symbol0"
但它没有打印任何东西......
我希望正则表达式只表示完全是“}”或“。”的字符串。 ,在同一行上没有任何后续或前面的字符。 有人知道我应该怎么改变它吗?
谢谢.. :))
答案 0 :(得分:2)
如果你需要以这种方式匹配字符串,你可以使用字符串开头和字符串结尾锚点:
open System.Text.RegularExpressions
let regexSymbol = new Regex("^[}.]$") // in this case verbatim is not required
if (regexSymbol.IsMatch(".")) then printfn "Matched! :)" else printfn "Not matched... :("
if (regexSymbol.IsMatch("}.")) then printfn "Matched! :)" else printfn "Not matched... :("
这会在第一行打印“匹配”,在第二行打印“不匹配”。
但是,检查此字符串是否等于“}”和“。”并不是更好吗?对不起,刚开始探索F#。
答案 1 :(得分:1)
问题在于什么是“。”不被视为单词边界。所以\ b“匹配'A”',但不匹配'。''。