Brandon Cunningham
Brandon Cunningham

Reputation: 41

Word boundary before special character fails the match

Here's what I've tried

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

where \x36 and \$ represent '$'

These are not returning a match, although the other keywords are.

Upvotes: 1

Views: 89

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627469

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.

Upvotes: 2

Related Questions