Page 1 of 1
match everything but..
Posted: Thu Jun 05, 2008 8:19 pm
by joeboentoe
Hello,
I am struggling with an expression.
I have sentences like:
1.The sky is blue
2.the sky is blue and violet
3.the sky is green
4.the sky is purple and violet
Now I need a regex who gives a match on sentence 1 and 3. So I want a match if the word violet is NOT on the end of a sentence. I know how to match a word and I know how to match if a character is not present [^character] and I know $ means 'end', but I don't know how to combine all those things for my goal.
thanks in advance.
Re: match everything but..
Posted: Fri Jun 06, 2008 12:59 am
by prometheuzz
joeboentoe wrote:Hello,
I am struggling with an expression.
I have sentences like:
1.The sky is blue
2.the sky is blue and violet
3.the sky is green
4.the sky is purple and violet
Now I need a regex who gives a match on sentence 1 and 3. So I want a match if the word violet is NOT on the end of a sentence. I know how to match a word and I know how to match if a character is not present [^character] and I know $ means 'end', but I don't know how to combine all those things for my goal.
thanks in advance.
You're close, but the negated character classes are not well suited for this task. Negative look behind is, however. This regex will do the trick:
which means: match any string, that when looking behind ('(?<!...)') from the end of the string ('$'), does not have the word 'violet'.
Here's a small demo:
Code: Select all
$tests = array(
'The sky is blue',
'the sky is blue and violet',
'the sky is green',
'the sky is purple and violet'
);
foreach($tests as $t) {
if(preg_match('/(?<!violet)$/', $t)) {
print "matched: $t\n";
}
}
HTH
Re: match everything but..
Posted: Fri Jun 06, 2008 9:43 am
by joeboentoe
thank you very much!
Re: match everything but..
Posted: Fri Jun 06, 2008 9:57 am
by joeboentoe
Okay I thought I had the solution, but now I need a regex that matches:
1.
blue is the sky
2.the sky is blue and
violet
3.
blue sky is green
4.the sky is purple and
violet
5.sky is violet and green
6.sky is yellow
A regex that matches 1,2,3 and 4. So if the word blue is at the beginning of a sentence OR if violet is at the end of a sentence, is that possible in one regex?
thanks
I know ^blue and violet$, but I don't know how to combine them in one regex, with an OR
EDIT: ^blue | violet$ does work

Re: match everything but..
Posted: Fri Jun 06, 2008 10:59 am
by prometheuzz
joeboentoe wrote:...
EDIT: ^blue | violet$ does work

That is correct, well done!