验证URL中的斜杠(/)的正则表达式

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

Regular expression to validate '/' in URL

问题

我正在使用golang编写一个Web应用程序。我正在使用正则表达式来验证URL。但是我无法在URL验证中包含'/'。

var validPath = regexp.MustCompile("^/(home|about)/(|[a-zA-Z0-9]+)$")

上述URL可以接受'/home/'、'/about/',但无法接受'/'。

请问有人可以帮我解决这个问题吗?

英文:

I am writing a web application in golang. I am using regular expression to validate the URL. But I am not able to include '/' in the URL validation.

var validPath = regexp.MustCompile("^/(home|about)/(|[a-zA-Z0-9]+)$")

The above URL takes '/home/', '/about/' but could not make for '/'.

Could anyone please help me on this?

答案1

得分: 3

为什么不将该案例作为一个替代方案添加进去:

"^/$|(/(home|about)/(|[a-zA-Z0-9]+)$)"
英文:

Why not adding that case as an alternative:

"^/$|(/(home|about)/(|[a-zA-Z0-9]+)$)"

答案2

得分: 1

你似乎想要可选的分组:

"^/(home|about)?(/[a-zA-Z0-9]+)?$"

演示

英文:

You seem to want optional groups:

"^/(home|about)?(/[a-zA-Z0-9]+)?$"

Demonstration

huangapple
  • 本文由 发表于 2015年8月15日 14:29:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/32022200.html
匿名

发表评论

匿名网友

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

确定