正则表达式匹配其中一个字符串

cnd*_*cnd 0 regex f#

        let m = Regex.Match(X.Text, "\\b(select)|(where)|(from)\\b", RegexOptions.IgnoreCase)
Run Code Online (Sandbox Code Playgroud)

它只突出了Select,所以我猜麻烦在于我的Regex.Match语法,但我看不到哪里?

与alll相关的变化我当前的解决方案看起来像这样:

module SQL_Highlighing

open System.Runtime.InteropServices

module Lock =
    [<DllImport(@"User32", CharSet = CharSet.Ansi, SetLastError = false, ExactSpelling = true)>]
    extern void LockWindowUpdate(int hWnd)

open System.Text.RegularExpressions
open System.Drawing

type SyntaxRTB() = 
    inherit System.Windows.Forms.RichTextBox()

    override X.OnTextChanged(e : System.EventArgs) =
        base.OnTextChanged(e); X.ColorTheKeyWords()

    member X.ColorTheKeyWords() =
        let HL s c =
            let color(m : Match, color : Color) =
                X.SelectionStart    <- m.Index
                X.SelectionLength   <- m.Length
                X.SelectionColor    <- color
            Regex.Matches(X.Text, "\\b" + s + "\\b", RegexOptions.IgnoreCase) |> fun mx ->
                for m in mx do if (m.Success) then color(m,c)

        let SelectionAt = X.SelectionStart
        Lock.LockWindowUpdate(X.Handle.ToInt32())

        HL "(select)|(where)|(from)|(top)|(order)|(group)|(by)|(as)|(null)" Color.Blue
        HL "(join)|(left)|(inner)|(outer)|(right)|(on)" Color.Red
        HL "(and)|(or)|(not)" Color.DarkSlateGray
        HL "(case)|(when)|(then)|(else)|(end)" Color.BurlyWood
        HL "(cast)|(nvarchar)|(bit)" Color.BlueViolet
        HL "(datepart)" Color.Teal

        X.SelectionStart    <- SelectionAt
        X.SelectionLength   <- 0
        X.SelectionColor    <- Color.Black
    Lock.LockWindowUpdate(0)
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 5

我建议使用正则表达式测试床.我发现GSkinner RegExr非常有用.

\ b表示边界,但是| 正在分离你的表达.你真正得到的是:

\b(select)
or
(where)
or
(from)\b
Run Code Online (Sandbox Code Playgroud)

我假设你想要每个边界,所以添加另一个组会阻止分离:

\b((select)|(from)|(where))\b
Run Code Online (Sandbox Code Playgroud)

  • +1这是另一个问题:)简化是`\ b(select | from | where)\ b`因为`|`具有最低优先级. (2认同)