正则表达式中的可选尾部斜线

Optional trailing slash in regex

https://embed.thatsite.com?id=
https://embed.thatsite.com/?id=

我试图在 ?id=

之前将尾部斜线设为可选

我试过了

https?:\/\/embed\.([^\/]*)\.com\/\?id=([0-9]+) //works with slash only
https:\/\/embed\.([^\/]*)\.com\?id=([0-9]+) //works without slash

因此,?id= 之前的尾部斜线应该是可选的,因为 embed.thatsite.com 随 url types.Is 发生变化,有任何方法可以使它成为 working.Thankyou

这应该有效:

https?:\/\/embed\.([^\/]*)\.com\/?\?id=([0-9]+)

这里,斜杠被改成?修饰符,会匹配前一个字符(/)0次或1次。

您可以使用 ?

/ 设为可选
https?:\/\/embed\.([^\/]*)\.com\/?\?id=([0-9]+)

https?:\/\/embed\. 匹配 http\embed.https\embed. 其中 s 是可选的 ?

([^\/]*) 匹配除 /

之外的所有内容

\.com\/?\?匹配.com和可选的/?字符

id=([0-9]+) 匹配 id= 并捕获尽可能多的数值

Regex Demo