正则表达式以禁止空字符串和逗号的形式为:^(?!$|,).*$

huangapple go评论146阅读模式
英文:

Regular expression to disallow empty string and comma

问题

我正在尝试编写一个正则表达式,以限制字符串中的空字符串和逗号。

示例:

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

这个正则表达式的目的是在Swagger文档中进行模式匹配,就像这个属性一样:type: string pattern: "^[0-9A-Za-z_]+$" value: type: object

我尝试了这个正则表达式 ^(?!\s*$)[^,]*$,但它在Swagger文档中不受支持,并且我在golang代码中使用这个正则表达式时出现了以下错误:

invalid or unsupported Perl syntax: `(?!

英文:

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

得分: 3

实际上,你不需要前瞻。

只需删除前瞻表达式,并将 * 更改为 +,这将要求至少一个字符,并简化你的正则表达式为 ^[^,]+$

如果这样可以解决问题,或者如果你有更多条件,请告诉我。

编辑:

考虑到 @JvdV 的评论(他似乎是对的),你可以使用以下正则表达式:

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

如果至少有一个非空白字符,这将匹配,并且如果有一个逗号的出现,整个字符串将被拒绝

查看此演示

编辑1:

为了避免灾难性回溯,可以将正则表达式简化如下:

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

解释:

  • ^ - 匹配输入的开头
  • \s* - 可选地匹配任何空白字符
  • [^,\s] - 匹配至少一个逗号和空白字符之外的字符
  • [^,]* - 可以跟随任何逗号之外的字符,零次或多次
  • $ - 匹配字符串的结尾

更新的演示

编辑2:为了避免前导/尾随空白字符,你可以使用以下正则表达式:

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

避免前导/尾随空白字符的演示

英文:

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

huangapple
  • 本文由 发表于 2022年8月14日 03:00:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/73346954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定