我需要验证应该像
google.com or
yahoo.co.uk etc
我的意思是我不需要http或www。我的正则表达式代码是这样的。但它对我不起作用。
/^[a-zA-Z0-9][a-zA-Z0-9-][a-zA-Z0-9]\.[a-zA-Z]{2,}$/
我需要验证应该像
google.com or
yahoo.co.uk etc
我的意思是我不需要http或www。我的正则表达式代码是这样的。但它对我不起作用。
/^[a-zA-Z0-9][a-zA-Z0-9-][a-zA-Z0-9]\.[a-zA-Z]{2,}$/
您当前的正则表达式不起作用,因为它需要在 之前正好三个字符.
:首先是匹配[a-zA-Z0-9]
的字符,然后是匹配的字符[a-zA-Z0-9-]
,然后是匹配的字符[a-zA-Z0-9]
。您的正则表达式只允许.
输入中的任何位置。
对于可变长度字符串,您需要使用+
or*
或{}
您对正则表达式最后一部分所做的语法。
要保持与您似乎正在拍摄的基本相同的验证,但让它适用于不同的长度,请尝试:
/^[A-Z\d-]+(\.[A-Z\d-]+)*\.[A-Z]{2,}$/i
那是:
[A-Z\d-]+
匹配一个或多个字母、数字或连字符,后跟
(\.[A-Z\d-]+)*
一个点的零个或多个实例,后跟一个或多个这些字符,然后是
\.[A-Z]{2,}
带有两个或更多 AZ 的最后一个点。
A-Z
请注意,如果将i
标志添加到正则表达式以使其不区分大小写,则可以仅使用大写范围。
Your original pattern wants to only allow urls that has the first part not start or end with a dash. In case that is important, I've made a pattern which does that for you.
/^(?:(?!-)[a-z\d-]+[^-]\.)+[a-z]{2,6}$/i
This fixes the same problems that nnnnn solved in his answer, but it also doesn't allow any part of the url to start or end with a hyphen.
I can also recommend regexpal to test matching in real time. It uses javascript style regex matching.
Put the regex into the top field and the test data in the bottom. You will need to remove the slashes encapsulating it. Check the box for "Case insensitive (i)" and "^$ match at line breaks (m)"
Some test data:
google.com
yahoo-.com
www.YAHOO.co.uk
-yahoo.co.uk
http://www.regular-expressions.info/
hey.subdomain.sub.sub.domain.com
co.uk
Now, the difference between using ^$ or not will prove itself. You will see that some urls are not matching, even though they are valid. The multiline (m) flag allows you to think of each line in the input as a separate string. The regex I gave you will only match if the entire string matches, but some urls are valid even so. Case insensitive (i) equals the "i" at the end of the regex.
Try to remove the anchors for start of line (^) and end of line ($), and see how that matches.
I'm not sure how you are running your matches, but this is worth considering.
尝试这个:
(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6}