简体   繁体   中英

Why does this REGEX not match specific literal?

I have this .NET regex:

(<%#)(?<type>((sql)|(magic)|(sqlscalar))):(?<method>([^\s]*)\s*)(\s)*(%>)

and it matches 'sqlscalar' and 'magic' perfectly , but does not match 'sql'

RegexTester截图

any help appreciated..

here is the server name <%#sqlscalar:@@servername %> this is result from funcA with @p valu=100 <%#sqlscalar:dbo.funcA(<%variableA%>)%> : both the functions above is in first line , Results of FuncB, and the fMagic() in second line <%#sqlscalar:funcB(<%variableB%>)%> <%#magic:fMagic()%> Third line is from sql 'select * from dbo.ftelUsers()' <%#sql:select * from dbo.ftElUsers()%>

Your regex doesn't allow whitespace after the colon (unless it's directly before the closing bracket %> ). That's why select * from... doesn't match.

I propose a different regex ( updated to handle nested tags which I had overlooked before):

Regex regexObj = new Regex(
    @"<%[#]         # Match '<%#'
    (?<type>        # Match and capture in group 'type':
     sql            # 'sql'
     (?:scalar)?    # optionally followed by 'scalar'
    |               # OR
     magic          # 'magic'
    )               # End of group 'type'
    :               # Match ':'
    (?<method>      # Match and capture in group 'method'
    (?>             # Either match (possessively):
     (?:            # the following group which matches
      (?!<%|%>)     # only if we're not at the start of <% or %>
      .             # any character
     )+             # once or more
    |               # or
     <% (?<Depth>)  # <% (and increase the nesting counter)
    |               # or
     %> (?<-Depth>) # %> (and decrease the nesting counter).
    )*              # Repeat as needed.
    (?(Depth)(?!))  # Assert that the nesting counter is at zero.
    )               # End of group 'method'
    %>              # Then match a closing %>.
    ", 
    RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);

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