[英]url validation RegExp recognize email address as url
I have to recognize url in some text. 我必须在某些文本中识别网址。 I use the following code (
this.value
is the text): 我使用以下代码(
this.value
是文本):
if (new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?").test(this.value)) {
alert("url inside");
}
The problem that is recognize also email address as url. 将电子邮件地址也识别为URL的问题。 How can I prevent it?
我该如何预防?
The expression /[a-zA-Z0-9_]/
is the same as /\\w/i
. 表达式
/[a-zA-Z0-9_]/
与/\\w/i
。
The original RegExp matches the "domain.org" substring in a text like "text name@domain.org text mailto:name@domain-2.org text". 原始RegExp与“ domain.org”子字符串匹配,例如“ text name@domain.org text mailto:name@domain-2.org text”之类的文本。 To fix this add
(?:^|[^@\\.\\w-])
at the beginning of the RegExp - a substring should be at the beginning of a line or should not begin with characters '@', '.', '-', '\\w'. 要解决此问题,请在RegExp的开头添加
(?:^|[^@\\.\\w-])
-子字符串应位于行的开头,或者不应以字符'@','。'开始, '-','\\ w'。
To exclude "mailto:user@..." substrings the expression ([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?
要排除“ mailto:user @ ...”子表达式的子字符串
([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?
should be modified. 应该修改。 Because Javascript RegExp has no look-behind expressions the only way to exclude "mailto" is to use the look-ahead expression
\\w(?!ailto:)\\w+:
, but all substrings like "[a-zA-Z0-9_]ailto:...@..." will be excluded also. 因为Javascript RegExp没有后向表达式,所以排除“ mailto”的唯一方法是使用前向表达式
\\w(?!ailto:)\\w+:
但是所有子字符串都类似于“ [a-zA-Z0-9_ ] ailto:... @ ...”也将被排除。
To exclude from matches the substring "user.name" from a text like "text user.name@domain.org text" add the expression (?=$|[^@\\.\\w-])
at the ending of the RegExp - match a substring only if the end of line follows the substring or the following characters '@', '.', '-', '\\w' don't follow the substring. 要从匹配项中排除“ text user.name@domain.org text”之类的文本中的子字符串“ user.name”,请在RegExp的末尾添加表达式
(?=$|[^@\\.\\w-])
-仅当行尾在子串之后或以下字符'@','。','-','\\ w'不跟随子串时,才匹配子串。
var re = /(?:^|[^@\\.\\w-])([a-z0-9]+:\\/\\/)?(\\w(?!ailto:)\\w+:\\w+@)?([\\w.-]+\\.[az]{2,4})(:[0-9]+)?(\\/.*)?(?=$|[^@\\.\\w-])/im; //if (re.test(this.value)) { // alert("url inside"); //} var s1 = "text name@domain.org name.lastname@domain-2.org text mailto:user.name@domain-3.org text"; if (re.test(s1)) { alert("Failed: text without URL"); } var s2 = "text http://domain.org/ text"; if (!re.test(s2)) { alert("Failed: text with URL"); } alert("OK");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.