.NET Framework Developer Center > .NET Development Forums > Regular Expressions > Changing regex so that it does not match words beginning with *?
Ask a questionAsk a question
 

AnswerChanging regex so that it does not match words beginning with *?

  • Saturday, October 31, 2009 2:11 AMnaturefreak827 Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    How would I change the regex "\b(\w|['-])+\b" so that it does not match words that start with *? I've tried to do it myself, but it is way beyond my knowledge of regular expressions.

Answers

  • Saturday, October 31, 2009 3:05 AMAhmad Mageed Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code
    You can add a lookaround to match if the prefix is absent: (?<!\*)

    string input = "*Hello, World... Regex: it's *an art!";
    string pattern = @"(?<!\*)\b(\w|['-])+\b";
    foreach (Match m in Regex.Matches(input, pattern))
    {
    	Console.WriteLine(m.Value);
    }
    


    Document my code? Why do you think it's called "code"?

All Replies

  • Saturday, October 31, 2009 3:05 AMAhmad Mageed Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     AnswerHas Code
    You can add a lookaround to match if the prefix is absent: (?<!\*)

    string input = "*Hello, World... Regex: it's *an art!";
    string pattern = @"(?<!\*)\b(\w|['-])+\b";
    foreach (Match m in Regex.Matches(input, pattern))
    {
    	Console.WriteLine(m.Value);
    }
    


    Document my code? Why do you think it's called "code"?