简体   繁体   English

如何创建自定义有效 Url 正则表达式

[英]How to create custom valid Url Regex

I am trying to create a regex for first time for the URL having following conditions:我正在尝试为具有以下条件的 URL 第一次创建正则表达式:

  1. Starts with or without the www以或不以 www 开头
  2. Do not starts with http:// or https://不要以 http:// 或 https:// 开头
  3. Allowed special characters are: hyphen (-) and dot (.)允许的特殊字符有:连字符 (-) 和点 (.)
  4. Ends with a TLD like: .com, .io, .co.in, etc.以 TLD 结尾,例如:.com、.io、.co.in 等。

Some of the examples for reference:一些示例供参考:

Valid:有效的:

xyz.com
xyz-px.com
www.xyz.com
abc.xyz.px.io
www.abc.xyz.px.io

Invalid:无效的:

xyz-.com
xy_pm.com
http://xyz.io
https://xyz.io
http://www.pm.xyz
xy@pzzzz.com
xyz.io$#
www.xy
xyz.io-

I have created a regex我创建了一个正则表达式

/(^(??https|http):.\/\/(www\?.)[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\,[^\s]{2,})/gi

But it is not working as desired.但它没有按预期工作。

You might use你可能会使用

^[^\W_]+(?:[-.][^\W_]+)*\.(?:io|com)$

The pattern matches:模式匹配:

  • ^ Start of string ^字符串开头
  • [^\W_]+ Match 1+ word chars without an _ [^\W_]+匹配 1+ 个不带_的单词字符
  • (?:[-.][^\W_]+)* Optionally repeat matching . (?:[-.][^\W_]+)*可选地重复匹配. or - and 1+ word chars without _-和 1+ 个不带_的字符
  • \. Match a literal dot匹配文字点
  • (?:io|com) Match any of the alternatives (?:io|com)匹配任何选项
  • $ End of string $字符串结尾

Regex demo正则表达式演示

The modified regex is修改后的正则表达式是

/^(?!(https|http):\/\/)(?:www\.)?[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9](?:.[^\s\W]{2,})+$/gi

https://regex101.com/r/aNy8St/1 https://regex101.com/r/aNy8St/1

You can use您可以使用

^(?!(http|https):\/\/)(?:www\.)?(?:(?:[a-zA-Z0-9])(?:[-\.][a-zA-Z0-9])?)+(?:\.[a-zA-Z0-9]+)$

DEMO - REGEXR演示 - 正则表达式

And the flowchart is:流程图是: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM