简体   繁体   中英

Regex Match one of strings

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

it highlights only Select , so I guess the trouble is in my Regex.Match syntax, but I can't see where ?

with alll the changes my current solution is looking like this :

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)

I recommend using a regular expression test bed. I find GSkinner RegExr very useful.

\\b is representing a boundary, but | is separating your expression. What you actually get is:

\b(select)
or
(where)
or
(from)\b

I assume that you want the boundary for each, so adding another group would prevent the separation:

\b((select)|(from)|(where))\b

migrated from comment

Regex.Match will only give you the first match. Instead, you should use Regex.Matches .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM