Thread: Simple regex to find word but not containing some other words

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    2

    Simple regex to find word but not containing some other words

    Hi Everyone,
    I've been trying to do a RegEx, but I just can't seem to find the solution for it.

    I was hoping someone could help me do the following to find Test:

    Test55: Will be allowed
    TestABC: Will NOT be allowed

    Basically, if Test is followed immediately by anything else other than a case-insensitive letter (not [a-zA-Z]), then it will pass.

    Thank You
    Sean

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    A regex may be overkill. Assuming line contains your string, and only one instance of "Test" can occur in the string, you could do this:
    Code:
    #include <string.h>  /* strstr() */
    #include <ctype.h>   /* isalpha() */
    
    char *p;
    
    p = strstr(line, "Test");
    if (p)
    {
        if (!isalpha(*(p + 4)))
        {
            /* accepted */
        }
        else
        {
            /* rejected */
        }
    }
    else
    {
        /* "Test" is not in this line */
    }
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Registered User
    Join Date
    Sep 2013
    Posts
    2
    Thank you for your reply, oogabooga. You are right it is overkill for the purpose, but I would like to know if its possible and how is it done.

    Thanks

  4. #4
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    I see. Well, the usual suspects are GNU regex's, POSIX.2 regex's, and my favorite, PCRE - Perl Compatible Regular Expressions. Which are you using?

    It's most likely to be POSIX.2, I suppose. You could search for a tutorial: https://www.google.ca/search?q=examp...regex+tutorial
    (That is, of course, just one search possibility. Try looking for "example"s, etc.)

    Regular expressions are a topic unto themselves but definitely repay the effort to learn them.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Program that Counts words like a Unix word count
    By NewGuy2CProg in forum C Programming
    Replies: 5
    Last Post: 09-21-2012, 10:49 AM
  2. C Program that Counts Words like Unix word count
    By NewGuy2CProg in forum C Programming
    Replies: 8
    Last Post: 09-20-2012, 08:28 PM
  3. Words in a Word
    By amb110395 in forum C++ Programming
    Replies: 2
    Last Post: 06-14-2011, 12:51 PM
  4. Replies: 1
    Last Post: 04-27-2011, 10:56 PM
  5. Simple regular expression to find word in a string?
    By BC2210 in forum C Programming
    Replies: 1
    Last Post: 03-28-2010, 07:41 PM