正则表达式匹配一个 slug?

2022-08-30 21:28:06

我在创建正则表达式以匹配URL slugs时遇到问题(基本上是用单个破折号分隔的字母数字“单词”)

this-is-an-example

我想出了这个正则表达式:虽然它将字符串限制为仅字母数字字符和破折号,但它仍然会产生一些误报,如下所示:/[a-z0-9\-]+$/

-example
example-
this-----is---an--example
-

我对正则表达式非常糟糕,所以任何帮助将不胜感激。


答案 1

您可以使用以下命令:

/^
  [a-z0-9]+   # One or more repetition of given characters
  (?:         # A non-capture group.
    -           # A hyphen
    [a-z0-9]+   # One or more repetition of given characters
  )*          # Zero or more repetition of previous group
 $/ 

这将匹配:

  1. 开头的字母数字字符序列。
  2. 然后,它将匹配一个连字符,然后是一系列字母数字字符,0 次或更多次。

答案 2

一个更全面的正则表达式,它将匹配 slug 中的 ascii 和非 ascii 字符,这将是,

/^             # start of string
 [^\s!?\/.*#|] # exclude spaces/tabs/line feed.. as well as reserved characters !?/.*#
 +             # match one or more times
$/             # end of string

为了更好地衡量,我们排除了保留的URL字符

因此,例如,上述内容将匹配

une-ecole_123-soleil
une-école_123-soleil
une-%C3%A9cole-123_soleil

推荐