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

时间:2011-03-24 10:58:00

标签: regex f#

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

它只突出显示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)

2 个答案:

答案 0 :(得分:5)

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

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

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

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

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

答案 1 :(得分:4)

从评论中迁移

Regex.Match只会给你第一场比赛。相反,您应该使用Regex.Matches