简体   繁体   English

javascript正则表达式不起作用

[英]javascript regular expression not working

I am trying to validate a textbox to ensure that a URL is written inside (minus the "http://" part). 我正在尝试验证文本框,以确保在其中写入URL(减去“ http://”部分)。 Here is my code: 这是我的代码:

var isUrl;
var regex = new RegExp("^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)");
var siteUrl = e.target.value;
if (siteUrl.match(regex)) {
   isUrl = true;
}
else {
   isUrl = false;
}

So my regular expression is ^(?!http)(www\\.)?(([az])+\\.[az]{2,}(\\.[az]{2,})?) . 所以我的正则表达式是^(?!http)(www\\.)?(([az])+\\.[az]{2,}(\\.[az]{2,})?) I was under the impression that this would do the following: 我的印象是,这将执行以下操作:

  1. NOT match anything beginning with http .. which it does correctly 不开始匹配任何http ..它不正确
  2. Allow an optional www. 允许一个可选的www. at the start 在开始时
  3. Accept 1 or more characters from az to be typed in 接受来自z的1个或多个字符以进行输入
  4. Accept a dot after those characters 在这些字符后接受一个点
  5. Accept 2 or more characters following the dot, and 点后接受两个或更多字符,并且
  6. Allow an optional dot followed by two or more characters again. 允许一个可选的点,然后再输入两个或多个字符。

In practice, the textbox accepts strings like "ashdiguasdf" and "aksjdnfa:://',~" which it should not do. 实际上,该文本框接受诸如“ ashdiguasdf”和“ aksjdnfa :: //',〜”之类的字符串,不应使用。 Can anyone explain why? 谁能解释为什么?

The main problem is that you're using the \\ character in a quoted string, which javascript will interpret as the start of a "control character" (such as \\n for a newline, etc). 主要问题是您在带引号的字符串中使用\\字符,而javascript会将其解释为“控制字符”的开头(例如\\n表示换行符,等等)。

One option is to escape it by replacing \\ with \\\\ . 一种选择是通过将\\替换为\\\\来对其进行转义。

But the easiest solution is to use the following format... 但是最简单的解决方案是使用以下格式...

var regex = new RegExp(/^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)/);

This also allows you to make it case insensitive (if you wish) by using the i character at the end, like this... 这还允许您通过在结尾使用i字符来使其不区分大小写(如果需要),如下所示...

var regex = new RegExp(/^(?!http)(www\.)?(([a-z])+\.[a-z]{2,}(\.[a-z]{2,})?)/i);

As an extra bit, you're using more capture groups than really necessary. 另外,您使用的捕获组超出了实际需要。 Your expression could also be written like this with the same result... 您的表达式也可以这样写,结果相同。

^(?!http)(?:www\.)?[a-z]+(?:\.[a-z]{2,}){1,2}

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

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