Regular expression to disallow empty string and comma

890 Views Asked by At

I'm trying to write regular expression to restrict empty string and comma inside a string

example:

string = "" # not allowed
s = "ab c!@#)(*&^%$#~" # allowed
s = "sfsfsf,sdfsdf" # not allowed

The intention of this regexp is to do a pattern matching in swagger documentation like this property: type: string pattern: "^[0-9A-Za-z_]+$" value: type: object

I tried this regular expression ^(?!\s*$)[^,]*$ but it is not supported inside swagger doc and I get this error in golang code for this regular expression:

invalid or unsupported Perl syntax: `(?!

1

There are 1 best solutions below

6
Pushpesh Kumar Rajwanshi On BEST ANSWER

You actually don't need a look ahead.

Just remove that lookahead expression and change * to + which will require at least one character and simplify your regex to ^[^,]+$

Let me know if that works or if you have more conditions.

Edit:

Considering @JvdV's comment (and he seems right), you can use following regex,

^\s*([^,\s]+\s*)+$

This will match if there is at least one non whitespace character and whole string will be rejected if there is even a single occurrence of a comma

Check this demo

Edit1:

To avoid catastrophic backtracking, the regex can be simplified as following,

^\s*[^,\s][^,]*$

Explanation:

  • ^ - Match start of input
  • \s* - Optionally match any whitespaces
  • [^,\s] - Match at least one character other than comma and whitespace
  • [^,]* - Can be followed by any character other than comma zero or more times
  • $ - Match end of string

Updated Demo

Edit2: For avoiding leading/trailing whitespaces, you can use this regex,

^[^\s,]([^,]*[^\s,])?$

Demo avoiding leading/trailing whitespaces