匹配连续 - 的正则表达式.或 .-(连字符和点)在字符串中 [英] Regular Expression to match consecutive -. or .- (hypen and dot) in a string

查看:42
本文介绍了匹配连续 - 的正则表达式.或 .-(连字符和点)在字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,其中连续 -.或 .- 不应出现在 URL 中.

I have a scenario where consecutive -. or .- should not be allowed in a URL.

例如.https://www.test.-nichttps://www.test-.nichttps://www.test.nic--xn/ 应该被允许

Eg. https://www.test.-nic or https://www.test-.nic whereas https://www.test.nic--xn/ should be allowed

你能帮我改进这个正则表达式吗?

Can you help me improve this regular expression?

/^(http|https|ftp):\/\/[a-z0-9]+(.[a-z0-9-]+)*.[a-z0-9]{2,5}(:[0-9]{1,5})?(\/.-‌​*)?$/i

推荐答案

您可以使用否定前瞻:

/^(https?|ftp):\/\/(?=.*?(?:\.-|-\.)[a-z0-9]+(\.[a-z0-9-]+)*\.[a-z0-9]{2,5}(:[0-9]{1,5})?$/i

(?=.*?(?:\.-|-\.) 是一个否定前瞻,如果 ._ 将导致匹配失败-. 是否在 URL 中.

(?=.*?(?:\.-|-\.) is a negative lookahead that will fail the match if ._ or -. are there in the URL.

这篇关于匹配连续 - 的正则表达式.或 .-(连字符和点)在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆