这个正则表达式有什么问题?(使用“。”)

时间:2020-12-31 18:33:35

I wrote the following code in F# :

我用f#写了如下代码:

let regexSymbol = new Regex(@"\b\}|\.\b")
if (Regex.IsMatch(".", regexSymbol.ToString())) then
    printfn "symbol0"

But it doesn't print anything..

但它什么都不印。

I'd like the regex to represent only strings that are exactly "}" or "." , without any following or preceding characters on the same line. Anyone knows how I should change it please?

我希望regex只表示恰好为“}”或“”的字符串。,在同一行上没有任何跟随或前面的字符。有人知道我该怎么换吗?

Thanks.. :)

谢谢. .:)

2 个解决方案

#1


2  

If you need to match strings that way, you'd use beginning-of-string and end-of-string anchors:

如果你需要这样匹配字符串,你应该使用开始-字符串和结束-字符串锚:

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... :("

This prints "Matched" at the first line, and "Not Matched" at the second.

第一行打印“匹配”,第二行打印“不匹配”。

But isn't it better just to check whether or not this string equal to "}" and '.'? Sorry, just starting exploring F#.

但是仅仅检查这个字符串是否等于“}”和“。”不是更好吗?抱歉,刚开始探索f#。

#2


1  

The problem is that what a "." isn't considered a word boundary. So \b" matches 'A"', but not '."'.

问题是,a“。”并不是一个词界。所以\b“匹配”A“,但不匹配”。

#1


2  

If you need to match strings that way, you'd use beginning-of-string and end-of-string anchors:

如果你需要这样匹配字符串,你应该使用开始-字符串和结束-字符串锚:

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... :("

This prints "Matched" at the first line, and "Not Matched" at the second.

第一行打印“匹配”,第二行打印“不匹配”。

But isn't it better just to check whether or not this string equal to "}" and '.'? Sorry, just starting exploring F#.

但是仅仅检查这个字符串是否等于“}”和“。”不是更好吗?抱歉,刚开始探索f#。

#2


1  

The problem is that what a "." isn't considered a word boundary. So \b" matches 'A"', but not '."'.

问题是,a“。”并不是一个词界。所以\b“匹配”A“,但不匹配”。