Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write a regular expression to match lines not ending with a phrase?

Tags:

regex

php

I need a PHP regular expression that matches a line beginning, but not ending, with a phrase. Something like:

$s = 'top bus stop';
$b = preg_match('/^top.*(?!top)$/', $s);

But one that actually works. What do you think?

like image 495
beej Avatar asked Jun 06 '11 18:06

beej


People also ask

How do I match an entire line in regex?

To expand the regex to match a complete line, add ‹ . * › at both ends. The dot-asterisk sequences match zero or more characters within the current line.

How do I match any character across multiple lines in a regular expression?

So use \s\S, which will match ALL characters.

Which regular expression matches the end of the line?

End of String or Line: $ The $ anchor specifies that the preceding pattern must occur at the end of the input string, or before \n at the end of the input string. If you use $ with the RegexOptions. Multiline option, the match can also occur at the end of a line.


1 Answers

You had it almost right. But the final assertion should be (?<!top) a lookbehind assertion using a < prefix. This way it really looks at the preceding three characters before the $ subject end.

like image 90
mario Avatar answered Oct 06 '22 01:10

mario