Prof. Falken
Prof. Falken

Reputation: 24877

Detect non-empty string with regexp?

How do I write a PHP regexp which detects that a string is not empty?

Empty means, in this case 0 characters. A single space, or a single newline counts as not empty, for instance.

(It has to be regexp suitable for preg_match(), since I have a lookup table with various regexps and don't want to handle this case in any special way, it would complicate the code to not use a regexp here.)


I also can not use any regex modifiers such as "s" outside the // for sad reasons.

Upvotes: 2

Views: 5769

Answers (3)

Danon
Danon

Reputation: 2973

  1. Character class with exclusive and complete classes: /[\w\W]/, /[\s\S]/, /[\d\D]/.
  2. Negative look-ahead on end of string: /(?!=\z)/ or /(?!=$)/D
  3. Unicode Any class: /\p{Any}/u, also matches newline
  4. Period in single-line mode: /./s
  5. Alteration of . and newline: /.|\n/

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

/[\s\S]/

matches any character, even if you can't use the /s modifier.

You don't need a quantifier (+) because if one character matches, then the condition is already fulfilled.

Upvotes: 10

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Just an idea (matches at least 1 of anything) :

/.{1,}/
  • or, even shorter version (as @tigrang suggested) : /.+/
  • or, even more complete version (including @BartKiers suggestion for newline support) where the s modifier causes the . meta char to match \r and \n as well:

    /.+/s
    

Upvotes: 7

Related Questions