Home > Software design >  Regex match only allow specific words and disallow anything before
Regex match only allow specific words and disallow anything before

Time:11-20

I have this injection VB script that I use for altering C# source code. This is my current regex match rule I use currently to find code rows with classes in the files:

(public|protected|internal|private|static|abstract)\b\W (class)\b

It works and detects class rows, but the problem is it detects all cases in the examples below, while only the first one should be valid.

public class  <-- is valid match
//this is a public class comment    <-- Should not be valid as match
"This is just a string talking about a public class"    <-- Should not be valid match

To me, what is missing is to have this match rule work is, only allow what is matched by allowed words, and make any other extra a non valid match. Well, a blank space should be the only type that should be allowed.

How to update the current regex to only match the first line of the three examples I just gave?

CodePudding user response:

You can use ^\s* to indicate it has to be at the start of a line, followed by 0 or more spaces:

^\s*(public|protected|internal|private|static|abstract)\b\W (class)\b

regex101

CodePudding user response:

If the { following the class name can be used to distinguish your 3 cases, you could modify your regex this way:

(public|protected|internal|private|static|abstract)\b\W (class)\b\s*[\r\n]{0,2}\s*{
  • Related