Vajura
Vajura

Reputation: 1132

A regex expression in C# help needed

My current regex looks somewhat like this:

(?<name>[\w\-"]+)[ \n]+MODULE-IDENTITY

It searches for MODULE-IDENTITY and then returns the word (with - and " symbols) that comes before. Now i want to add something that will check if the word before MODULE-IDENTITY is lets say DOG it wont result in a match.

Can anybody help?

Upvotes: 0

Views: 92

Answers (3)

faby
faby

Reputation: 7558

this is the regEx that exclude the word dog

(?<name>\b(?!\bdog\b)[\w\-"]+\b+)[ \n]+MODULE-IDENTITY

I use word boundary \b to allow the RegEx to match words like hot-dog that contains the word to exclude

try it with http://regexhero.net/tester/

if you put input
hi cat MODULE-IDENTITY test --> match found "cat MODULE-IDENTITY"
and if you input
hi dog MODULE-IDENTITY test --> no matches found

c# code

string strRegex = @"(?<name>\b(?!\bdog\b)[\w\-""]+\b+)[ \n]+MODULE-IDENTITY";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant);
string strTargetString = @"hi dog MODULE-IDENTITY test";

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    // in this case no matches found because of "dog" word in input
   }
 }

Upvotes: 0

The way write the regular expression to check for any words before the MODULE-IDENTITY is given in:Regex: A-Z characters only However you need to have a IsMatch check, like: System.Text.RegularExpressions.Regex.IsMatch(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase), where s is your input string, sPattern is your regular expression, and the last argument are some options for making the match.

Upvotes: 0

dyson
dyson

Reputation: 886

For this specific example:

(?<name>[\w\-"]+)(?<!DOG)[ \n]+MODULE-IDENTITY

This will match e.g.

testing
MODULE-IDENTITY

but not

DOG
MODULE-IDENTITY

Upvotes: 1

Related Questions