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.
match everything but..
Moderator: General Moderators
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: match everything but..
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: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.
Code: Select all
'/(?<!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";
}
}-
joeboentoe
- Forum Newbie
- Posts: 3
- Joined: Thu Jun 05, 2008 8:11 pm
Re: match everything but..
thank you very much!
-
joeboentoe
- Forum Newbie
- Posts: 3
- Joined: Thu Jun 05, 2008 8:11 pm
Re: match everything but..
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
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
- prometheuzz
- Forum Regular
- Posts: 779
- Joined: Fri Apr 04, 2008 5:51 am
Re: match everything but..
That is correct, well done!joeboentoe wrote:...
EDIT: ^blue | violet$ does work