正则表达式不应匹配两个或两个以上连续的破折号。

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

Regex should not match for two or more consecutive dashes

问题

我有以下正则表达式:

\p{Alpha}[\p{Alnum}-]+\p{Alnum}

使用这个正则表达式,文本应该以一个字母字符开头,然后可以由字母数字和短横线组成。

但是我不想要两个或更多连续的短横线。我可以用什么正则表达式来处理这种情况?

谢谢大家

Frank

英文:

I have the following regex:

\p{Alpha}[\p{Alnum}-]+\p{Alnum}

With this, the text should start with an alpha character and could be followed by alphanumerics and dashes.

But I don t want to have two or more consecutive dashes. What is the right regex that I can use for this case?

Thanks to all

Frank

答案1

得分: 4

你可以考虑使用这个正则表达式解决方案:

^\p{Alpha}\p{Alnum}*(?:-\p{Alnum}+)*$

正则表达式演示

正则表达式详情:

  • ^:开始
  • \p{Alpha}:匹配一个字母
  • \p{Alnum}*:匹配0个或多个字母数字字符
  • (?:-\p{Alnum}+)*:匹配-后跟1个或多个字母数字字符。重复此组0次或多次
  • $:结束
英文:

You may consider this regex solution:

^\p{Alpha}\p{Alnum}*(?:-\p{Alnum}+)*$

RegEx Demo

RegEx Details:

  • ^: Start
  • \p{Alpha}: Match an alphabet
  • \p{Alnum}*: Match 0 or more alphanumeric characters
  • (?:-\p{Alnum}+)*: Match - followed by 1+ of alphanumeric characters. Repeat this group 0 or more times
  • $: End

答案2

得分: -2

可能这将起作用

\p{Alpha}[\p{Alnum}-]+(?!-)\p{Alnum}

在这个模式中,(?!-) 是负向前瞻断言,确保在前一个匹配后面没有连字符。

英文:

Probably this will work

\p{Alpha}[\p{Alnum}-]+(?!-)\p{Alnum}

In this pattern, (?!-) is the negative lookahead assertion that ensures there is no dash immediately following the previous match.

huangapple
  • 本文由 发表于 2023年7月17日 21:51:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705137.html
匿名

发表评论

匿名网友

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

确定