Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex dont match if it is an empty string

Currently, I am using /^[a-zA-Z.+-. ']+$/ regex to validate incoming strings.

When the incoming string is empty or only contains whitespace, I would like the code to throw an error.

How can I check for empty string using regex? I found some solutions but none are helpful.

like image 345
Harsha Avatar asked Jan 30 '23 20:01

Harsha


2 Answers

You may use

/^(?! *$)[a-zA-Z.+ '-]+$/

Or - to match any whitespace

/^(?!\s*$)[a-zA-Z.+\s'-]+$/

The (?!\s*$) negative lookahead will fail the match if the string is empty or only contains whitespace.

Pattern details

  • ^ - start of string
  • (?!\s*$) - no empty string or whitespaces only in the string
  • [a-zA-Z.+\s'-]+ - 1 or more letters, ., +, whitespace, ' or - chars
  • $ - end of string.

Note that actually, you may also use (?!\s+) lookahead here, since your pattern does not match an empty string due to the + quantifier at the end.

like image 121
Wiktor Stribiżew Avatar answered Feb 01 '23 11:02

Wiktor Stribiżew


Check if the string is empty or not using the following regex:

/^ *$/

The regex above matches the start of the string (^), then any number of spaces (*), then the end of the string ($). If you would instead like to match ANY white space (tabs, etc.), you can use \s* instead of *, making the regex the following:

/^\s*$/
like image 34
Kiran Shahi Avatar answered Feb 01 '23 11:02

Kiran Shahi