简体   繁体   中英

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?

For this specific example:

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

This will match eg

testing
MODULE-IDENTITY

but not

DOG
MODULE-IDENTITY

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
   }
 }

在给出MODULE-IDENTITY之前,编写正则表达式以检查所有单词的方式: Regex:仅AZ字符但是,您需要进行IsMatch检查,例如:System.Text.RegularExpressions.Regex.IsMatch(s,sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase),其中s是您的输入字符串,sPattern是您的正则表达式,最后一个参数是进行匹配的一些选项。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM