Regex 正则表达式匹配字符串之一

Regex 正则表达式匹配字符串之一,regex,f#,Regex,F#,它只突出显示Select,所以我想问题在于我的Regex.Match语法,但我看不出在哪里 通过所有更改,我当前的解决方案如下所示: let m = Regex.Match(X.Text, "\\b(select)|(where)|(from)\\b", RegexOptions.IgnoreCase) 模块SQL\u高亮度 open System.Runtime.InteropServices 模块锁= [] 外部无效锁窗口更新(内部hWnd) 打开System.Text.R

它只突出显示Select,所以我想问题在于我的Regex.Match语法,但我看不出在哪里

通过所有更改,我当前的解决方案如下所示:

        let m = Regex.Match(X.Text, "\\b(select)|(where)|(from)\\b", RegexOptions.IgnoreCase)
模块SQL\u高亮度
open System.Runtime.InteropServices
模块锁=
[]
外部无效锁窗口更新(内部hWnd)
打开System.Text.RegularExpressions
开放系统.绘图
类型SyntaxRTB()=
继承System.Windows.Forms.RichTextBox()
重写X.OnTextChanged(e:System.EventArgs)=
base.OnTextChanged(e);X.颜色关键字()
成员X.ColorTheKeyWords()=
让我们来看看=
让颜色(m:匹配,颜色:颜色)=

X.SelectionStart我建议使用正则表达式测试床。我觉得很有用

\b表示边界,但|分隔表达式。你实际得到的是:

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)
我假设您需要每个组的边界,因此添加另一个组将防止分离:

\b(select)
or
(where)
or
(from)\b
从注释迁移


Regex.Match
只提供第一个匹配项。相反,您应该使用
Regex.Matches

我怀疑这与您的问题有关,但您的p/Invoke签名是错误的。它应该是
extern bool LockWindowUpdate(nativeint hWnd)
并且
SetLastError
应该设置为
false
。Hhm,它只会突出显示第一个选择,where或from。改用
Regex.Matches
。这可能就是问题所在(尚未测试您的代码)。另外,您想用
\\b
s实现什么?您真的希望输入数据中有退格文字吗?@lassespeholt将其添加到答案中,让mx=Regex.Matches(X.Text,\\b(select)|(where)|(from)\\b,\\RegexOptions.IgnoreCase)为mx中的m添加if(m.Success)然后使用颜色(m,color.Blue)解决了我的问题。@ildjarn当
\b
在字符类之外时,它的意思是“单词边界”,请参见+1,这是另一个问题:)简化将是
\b(选择| from | where)\b
,因为
的优先级最低。
\b((select)|(from)|(where))\b