none
正则表达式匹配“A & B & C”这样的表达式 RRS feed

  • 问题

  • 在vb.net中,正则表达式表示形如 A & B 这样的表达式该如何写?

    要求:

    1.A、B是数值或双引号括起来的字符
    2.遇到A & B & C的情况时,能从左到右匹配

    目前我自己写的是这样的:
    (?<A>\s*(?:\-?\d+\.?\d*)|(?:"{1}(.+)"{1}))(?<Operater>\s*[&]{1}\s*)(?<B>(?:\-?\d+\.?\d*)|(?:"{1}(.+)"{1})\s*)
    其中(?:\-?\d+\.?\d*)|(?:"{1}(.+)"{1})表示数值或以双引号括起来的字符

    但是测试   16& "-" & "1"   这样的情况时,匹配结果是{16}和{-" & "1}

    而我希望匹配{16}和{-}

    望高人不吝赐教,谢谢


    编程是永无止境的,向大家学习

    2017年5月16日 5:54

全部回复

  • Hi abcjackson,

    请把你的vb代码分享一下,并且解释一下 “.遇到A & B & C的情况时,能从左到右匹配” 和“A & B” 是什么意思,最后希望你给出一个测试字符串, 应用上面的正则表达式得到的是怎样的结果, 和你想要的结果有什么差距。

    谢谢您的支持。

    Best Regards,

    Cherry  


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2017年5月16日 8:37
    版主
  • 谢谢您的回复。

    我觉得您看代码的话可能反而会更费劲些:)

    代码如下:

          Imports System.Text.RegularExpressions

    Private m_Constants As Collection Private Const Number As String = "(\-?\d+\.?\d*)" '匹配数字,含符号和小数点 Private Const cStrings As String = "\w+" '"[a-zA-Z][u4e00-u9fa5]+"'匹配词或英文单词 Private Const AnyStrings As String = "(.+)" '表示匹配任何字符 Private AnyStringsWithParenthesis As String = "(""{1}" & AnyStrings & """{1})" '表示任何字符(字符串有双引号括着) Private NumberOrAnyStringsWithParenthesis = Number & "|" & AnyStringsWithParenthesis Private NumberOrAnyStringsWithParenthesisUnCapture = Number.Insert(1, "?:") & "|" & AnyStringsWithParenthesis.Insert(1, "?:") Private RegexStringAnd As Regex

            RegexStringAnd = New Regex("(?<A>\s*" & NumberOrAnyStringsWithParenthesisUnCapture & ")(?<Operater>\s*[&]{1}\s*)(?<B>" & NumberOrAnyStringsWithParenthesisUnCapture & "\s*)") '定义&运算符,&的两边必须是字符串(字符串有双引号括着)或数字
            Private Function DoStringAnd(ByVal m As Match) As String
                Select Case m.Groups(4).Value.Trim(" "c)
                    Case "&"
                        Return """"c & m.Groups(1).Value.ToString & m.Groups(2).Value.ToString & """"c
                    Case Else
                        Throw New Exception("没有匹配的预定义运算符")
                End Select
            End Function


    ExpressionString = "16& ""-"" & ""1"""

    Do While RegexStringAnd.IsMatch(ExpressionString)
        ExpressionString = RegexStringAnd.Replace(ExpressionString, AddressOf DoStringAnd)

    Debug.Print(ExpressionString)

    Loop

    Debug返回的结果是"""-"" &""1"""

    希望输出的结果是"16-1",问题出在匹配双引号上,DoStringAnd函数的m.Groups匹配到{}、{-"" &""1}、{16}、{& }、{"-" &"1"},5个部分


    编程是永无止境的,向大家学习



    2017年5月17日 4:24