简体   繁体   English

Javascript:正则表达式中的空字符串匹配

[英]Javascript : Empty String Match In Regular Expression

i want to match the url with contatin http/https and (www) or without (www) with the help of regular expression. 我想在正则表达式的帮助下,将带有匹配http/https(www)或不带有(www)的URL进行匹配。 following is my regualr expression 以下是我的正式表达

^((https?)://)(www\\.)| ^$ +(\.[a-z0-9-]+)+([/?].*)?$

but in this, the empty string is not work for example : when i enter http://www.google.com is valid url but http://google.com is not valid. 但是在这种情况下,例如,空字符串不起作用:当我输入http://www.google.com是有效的URL,而http://google.com无效时。 thanks for the answer in advance. 谢谢你提前回答。

You can't search for an not existing part using ^$ . 您无法使用^$搜索不存在的零件。 that is expecting a start of a string(row), end of the string (row). 期望一个字符串(行)的开始,字符串(行)的结束。

Just make the "www" part optional: 只需将“ www”部分设为可选:

^((https?)://)(www\\.)?(\.[a-z0-9-]+)+([/?].*)?$

another problem is, you are searching for two dots in a row: 另一个问题是,您正在连续搜索两个点:

^((https?)://)(www\\.)?(\.[a-z0-9-]+)+([/?].*)?$
                    ^    ^

I think a better pattern would be 我认为更好的模式是

^((https?)://)(www\\.)?([a-z0-9-]+)(\.[a-z0-9-]+)*([/?].*)?$

Are you aware, that you are excluding a lot of valid URLS, by only allowing the characters [a-z0-9-] ? 您是否知道,仅允许使用字符[a-z0-9-]来排除大量有效的URL?

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

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