开发者

Regex Forward and Backward looking patterns

Hi I am very new to regex but would like to construct something that will match on the word "Public" | "Private" | "Protected" and the following word (to grab the following word), unless the following word is not: void, string, int, bool. The bolded word matches can be any word except for the ones listed above.

Sample Matches:

  • Public xyz Functionname (match)
  • Public abc Functionname (match)
  • Private rbc Functionname (match)
  • Protected klm Functionname (match)

Sample Non-matches:

  • Public void Functionname (non-match)
  • Public string Functionname (non-match)
  • Public int Functionname (non-match)

I got as far as this but it's not really working properly:

^(开发者_如何转开发(Public)|(Private)|(Protected)).*$(?<!Void|string|int)


Try this:

\b(?:public|private|protected)\s+(?!void|string|int|bool)(\w+)\s+

After a word break, match (but don't capture) public or private or protected, then one or more whitespace characters, then one or more "word" characters as long as the word is not void or string or int or bool.

Seems to work in my tests.

Edit To exclude matches that end with get; or set;, it's a bit more complicated but this appears to work:

\b(?:public|private|protected)\s+(?!void|string|int|bool)(\w+)\s+((?!(get;|set;)$).)*$

which I just like the first one with the addition of followed by any number of any character that is not followed by a get; or a set; which ends the line

That will match Public xyz Functionname get; with other stuff but not Public xyz Functionname get;. If the former should be excluded as well, just drop the second to last $, and then a match will be discarded if there's a get; or set; anywhere after the first section.


This is what you need:

^(Public|Private|Protected) (?!void|string|int).*$


Your question doesn't seem to jibe with your examples, but this matches the examples:

^(Public|Private|Protected)\s+(?!void|string|int|bool)(\w+)\s+(\w+)

Basically, you want to use lookahead, not lookbehind. Lookbehinds aren't nearly as useful as most people expect them to be. In fact, most regex flavors would treat your lookbehind as a syntax error.


The previous answers do not properly utilize word boundaries and will fail for the following:

foopublic abc (FactorMystic's regex)
Public voidxyz Functionname (Alan Moore's regex)

In most programming languages, a variable identifier which contains a reserved word with additional characters is still valid. For example, if function is a reserved word, a variable identifier of myfunction is still valid.

Here is a revised regex:

\b(Public|Private|Protected)\s+(?!(?:void|string|int|bool)\b)(\w+)

If you are using this for syntax highlighting, I recommend writing an actual parser. Regex-based syntax highlighters can be inaccurate, and most flavors of regex aren't particularly great when dealing with nested constructs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜