正则表达式 - 匹配字符但不匹配正斜杠

Regex - Match the characters but not the forward slash

我实际上是在寻找正则表达式。基本上我想匹配下面的 URL

/test/*/contact/*

我的输入是这样的

/test/1234/contact/abcd  ----   This is correct
/test/abcd/1234/contact/abcd --- This should show not match

我试过正则表达式

\/test\/\S+\/contact\/\S+

使用上面的 exp 表明两者都是正确的。谁能帮我排除正斜杠?

\S 模式匹配 /。您应该依赖 [^\/] 否定字符 class 并使用锚点:

^\/test\/[^\/]+\/contact\/[^\/]+$

regex demo

详情

  • ^ - 字符串开头
  • \/test\/ - /test/
  • [^\/]+ - /
  • 以外的 1+ 个字符
  • \/contact\/ - /contact/
  • [^\/]+ - /
  • 以外的 1+ 个字符
  • $ - 字符串结尾。

\S 表示 "Anything that isn't \s"。

\s 表示 "whitespaces"。它等于:[\r\n\t\f\v]

  • \r - 马车return
  • \n - 换行符
  • \t - 选项卡
  • \f - 换页符(类似于 "next page")
  • \v - 垂直 space
  • </code>-简单白space</li> </ul> <p>因此,<code>\S 包括 + /。为了实现你想要的,你可以做类似 "anything but spaces or slashes" 的事情(即:[^\/\s]*)或指定你接受的字符(例如,对于字母数字和 -_ 它将是:[a-zA-Z0-9_-]*).

    如果您有任何问题,请随时提出,我会进一步解释