none
RegEx Question: Match whole word from substring

    Question

  • Hello, I want to search a buffer using a search pattern and return whole words that contain the search pattern .

    Here's a sample Buffer:  "CADLOG  cat red green NAR_LOG bus stay logroll house mouse fur log crutch"

    Here's my search string: log

    I would like this to return matches: CADLOG, NAR_LOG, logroll, log

    Using System.Text.RegularExpressions I can match the substring within words, but I can't seem to return a whole word.

    Can someone help me with formatting what I'm sure is a basic regular expression?

    Thanks!!
    Tuesday, March 14, 2006 11:15 PM

Answers

  • Here's a pattern that should do what you are looking for:

    \b\w*log\w*\b

    For future regular expression needs, I would recommend checking out www.regexplib.com, which has a place to test expressions using the .NET engine.

    To Imran, please in the future, when posting code to the VB forums, try to use VB syntax if possible.
    Wednesday, March 15, 2006 3:06 PM

All replies

  • One simple way would be to split the string into words and then look for the pattern in each of those words. Not a very efficient technique but it'll work:

    Regex r = new Regex("log", RegexOptions.IgnoreCase);
    List<string> matches = new List<string>();
    string str = "CADLOG cat red green NAR_LOG bus stay logroll house mouse fur log crutch";

    foreach(string word in str.split(' '))
    {
        if r.IsMatch(word)
        {
           matches.Add(word);
        }
    }

    Your list should have all the matching words.

    hope that helps,
    Imran.
    Wednesday, March 15, 2006 3:34 AM
  • Here's a pattern that should do what you are looking for:

    \b\w*log\w*\b

    For future regular expression needs, I would recommend checking out www.regexplib.com, which has a place to test expressions using the .NET engine.

    To Imran, please in the future, when posting code to the VB forums, try to use VB syntax if possible.
    Wednesday, March 15, 2006 3:06 PM
  • Apologies. I usually hang out in both C# and VB groups. Somehow I thought I was in a C# group and that is why I wrote the C# code. Believe it or not, I actually write more code in VB than in C#. So it's not like I'm a language fanatic :)

    Imran.
    Wednesday, March 15, 2006 4:21 PM
  • Thanks guys!!

    I implemented the code in straight vb using INSTR(), but I'm glad to be able to compare the performance using the REGEX pattern.

    I appreciate your help!


    Wednesday, March 15, 2006 5:01 PM
  • Congradulations,

    You might want to check out a regex tutoral, such as:

    http://www.regular-expressions.info/

    Please give credit where credit is due and mark this quest as answered.

    Friday, March 17, 2006 3:30 PM