none
Regex question. returning match if word is found on line but only if a certain other word is not also found on same line RRS feed

  • Question

  • Hello,

    I see the RegEx forum is closed and there is a pointer to this site. Can someone please assist me with the following question (I am using PowerShell)

    I am trying to do something that at first I thought would be simple (I guess like any thing it is simply when you know the answer)

    I need to check a line of text for a phrase and match as True if that word appears in the line of text. However I need the whole match to fail i..e return false if another certain word appears on the same line of text.

    for example

    "some text good some more text"

    Look for the word "good" positive match needs to return true i.e. match found (easy)

    "some text more test good some more text bad some more text"

    now if the line contains good and bad as above (cannot say in advance how many characters may be between the two words) I need the overall match to fail and not match i.e. false.

    Therefore I have tried serious combinations of a negative look ahead like so.

    good(?!bad)
    good.+?(?!bad)
    good(?!bad).*
    good(?!bad).+

    etc

    nothing works for the line containing the words "good" and "bad"  I  I get a match and therefore true.
    As I do not know how many characters will appear between the words in question I cannot use a literal number of .... (that would work) therefore I need to say "good" following by any number of characters as long as those characters do not contain the phrase bad.

    Can you help please, thanks in advance
    Ernie

    Monday, January 14, 2013 6:36 PM

Answers

  • Try this pattern:

        good(?!.+bad)

    To differentiate “good” and “goods” etc., consider ‘\b’.


    • Edited by Viorel_MVP Tuesday, January 15, 2013 7:07 AM
    • Marked as answer by BrantEH Tuesday, January 15, 2013 8:43 AM
    Tuesday, January 15, 2013 7:06 AM

All replies

  • Try this pattern:

        good(?!.+bad)

    To differentiate “good” and “goods” etc., consider ‘\b’.


    • Edited by Viorel_MVP Tuesday, January 15, 2013 7:07 AM
    • Marked as answer by BrantEH Tuesday, January 15, 2013 8:43 AM
    Tuesday, January 15, 2013 7:06 AM
  • Hello Viorel

    That worked perfectly, thanks very much, I can see why you are an MVP :)

    Ernie

    Tuesday, January 15, 2013 8:42 AM