9

Possible Duplicate:
A Regex that will never be matched by anything

I have a script that takes a regex as a parameter. By default I want to set the regex to something that will never match any string, so I can simply say

if ($str =~ $regex)

without e.g. having to check defined($regex) first.

I came up with

qr/[^\s\S]/

but don't know if this will match some utf8 character that is neither a space nor a non-space.

Community
  • 1
  • 1
Jonathan Swartz
  • 1,773
  • 2
  • 16
  • 27

3 Answers3

20
/(?!)/

http://perl.plover.com/yak/regex/samples/slide049.html

Hugmeir
  • 1,239
  • 6
  • 9
  • MJD’s solution is better than anything else offered here or on the alleged dup question that this deserves to be kept. – tchrist Jan 04 '11 at 01:37
  • @tchrist: From my admittedly narrow point of view, just about anything by MJD is pure gold. The man is a Perl Alchemist or something. – Hugmeir Jan 04 '11 at 02:31
  • To illuminate: the empty pattern `//` or `(?:)` doesn't assert anything, and therefore always matches. `(?!)` is a negative lookahead for the empty pattern (what comes between the `!` and the `)` is the body of the assertion) and therefore can never match. – hobbs Jul 24 '12 at 22:06
  • @hobbs: Nitpick: // *can* match something; it's the special empty pattern, which will reuse the last matched regex if there was one... :( – Hugmeir Aug 29 '12 at 09:09
  • @Hugmeir yeah, I didn't mean *that* `//`, but I guess it's a bit unclear :) – hobbs Aug 29 '12 at 13:40
5

Combine a negative lookahead for an arbitrary character followed by a match for that character, e.g.

/(?!x)x/

Works on all the test cases I threw at it. Here are some tests on rubular.

moinudin
  • 117,949
  • 42
  • 185
  • 213
4

/ ^/ seems to do, and is short(est).

user502515
  • 4,229
  • 22
  • 20