Home > Mobile >  Regular expression to restrict empty string and commas
Regular expression to restrict empty string and commas

Time:08-15

Im 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 internsion 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: `(?!`

Please help me with the regular expression

CodePudding user response:

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

  • Related