Word boundary before special character fails the match

前端 未结 1 1554
耶瑟儿~
耶瑟儿~ 2021-01-24 01:34

Here\'s what I\'ve tried

CSharpClassNameRegex = new Regex(@\"\\b(\\x36|class|\\$|function|struct|enum|interface)(?\\w+?)\\b\", RegexCompiledOption);         


        
相关标签:
1条回答
  • 2021-01-24 02:18

    The $ symbol is not a word char, and \b requires a word char before it.

    You may fix your regex using an unambiguous left word boundary, (?<!\w):

    CSharpClassNameRegex = new Regex(@"(?<!\w)(class|\$|function|struct|enum|interface)(?<range>\w+)", RegexCompiledOption);
    

    Note that \w+?\b can be replaced with \w+ safely, \w+ will greedily match 1 or more word chars and you do not have to enforce matching 1 or more word chars with a word boundary.

    Also, \x36 matches 6 char, so I doubt you need to keep it in the regex.

    Regex details

    • (?<!\w) - no word char is allowed immediately to the left of the current location
    • (class|\$|function|struct|enum|interface) - Group 1: class, $, function, struct, enum, interface substrings
    • (?<range>\w+) - Named group "range": 1 or more word chars.
    0 讨论(0)
提交回复
热议问题