Word boundary before special character fails the match

前端 未结 1 1555
耶瑟儿~
耶瑟儿~ 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, (?:

    CSharpClassNameRegex = new Regex(@"(?\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

    • (? - 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
    • (?\w+) - Named group "range": 1 or more word chars.

    0 讨论(0)
提交回复
热议问题