开发者

Regex Match one of strings

开发者 https://www.devze.com 2023-02-19 05:23 出处:网络
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 ?
        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.开发者_JAVA技巧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.

0

精彩评论

暂无评论...
验证码 换一张
取 消