tags:

views:

92

answers:

3

Possible Duplicate:
What regular expression can never match?

how do i write a regular expression which returns false always in php.

i wanted this bcos . i wanted to display a error msg with out a form rule...so i did like this..

if($values['result_msg'] == 'ERROR')
                    {
                    $form->registerRule('just_check','regex','/$^/');                       
                    $form->addRule('abc', 'Please enter valid Model Number.','just_check');
                    }
+5  A: 

I don't know why you want to do this, but this'll do it:

(?!x)x

The first bit (?!..) is a negative lookahead which says "make sure this position does not match the contents of this lookahead", where the contents is x, and then the final x says "match x" - since these two are opposites, the expression will never match.

You may also want to add start/end markers, i.e.

^(?!x)x$

You can swap both the x with pretty much anything, so long as both bits are equivalent.

There are plenty of other ways to do it, basically you just put two mutually exclusive conditions next to each other for matching the same place, and the regex will fail to match - see Mark's answer for more examples.

Peter Boughton
@Peter Boughton - wht is is trying to do?
pradeep
pradeep, there is an explanation there now. Although *you* haven't explained why you want this in the first place - there's probably a better solution.
Peter Boughton
@pradeep - @Peter told you what it was doing, what don't you understand?
slugster
slugster, StackOverflow doesn't show initial edits - there were four revisions to the post, not the one which the history currently shows.
Peter Boughton
+5  A: 

There are lots of ways to do it:

  • /(?=a)b/

This fails to match because it searches for a character which is both a and b.

  • /\Zx\A/

This fails to match because the end of the string cannot come before the start of the string.

  • /x\by/

This fails to match because a word boundary cannot be between the characters x and y.

Mark Byers
I like `$^` a lot.
Pekka
@Pekka: In PHP it's necessary to have a character between the $ and ^ otherwise it matches the empty string, `$x^` for example.
Mark Byers
@Mark true! Remembered that one wrong ` ` ` `
Pekka
A: 

Try this out:

$.^
Johnny Saxon
If multiline dotall flag is enabled, would this not match a newline character?
Peter Boughton
@Peter: no. pay attention to the order of `$` and `^`.
nikic
nikic, pay attention to what I'm saying! If multiline flag is enabled, `$` matches "end of line" and `^` matches "start of line". If dotall flag is enabled `.` matches newline. Therefore, with multiline+dotall flags, `$.^` will match the newline (\n) character in `x\ny`.
Peter Boughton
(I've tested this with both Java and CF regex engines, and have verified this behaviour with those - I don't have a PHP setup handy to check for that.)
Peter Boughton
Ah hadn't thought of multiline! Thanks for the enlightenment Peter.
Johnny Saxon