简体   繁体   English

如何使用正则表达式验证至少3个单词的句子且不允许使用URL

[英]how to validate sentence of minimum 3 words and no URL allowed using regular expression

I wanted to create a regex to validate a minimum of 3 words and no URL allowed: 我想创建一个正则表达式来验证至少3个单词并且不允许使用URL:

Here's the regex I have so far for a minimum of 3 words: 这是我到目前为止至少三个单词的正则表达式:

"minimumThreeWordsAndNoURL": {
                    "regex": /^/\b\w{1,2}\b/$/,
                    "alertText": "Minimum of 3 words and no URL allowed"
                },

and here's the regex for the URL 这是URL的正则表达式

 "url": {
                "regex": /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,
                "alertText": "* Invalid URL"
            },

how do I combine this such that I want 3 words and no URL are allowed in the textarea? 如何将其组合在一起,以便在文本区域中需要3个单词且不允许使用URL?

Chaitanya raises a valid point: unless you're playing Regex Golf or solving a homework assignment, you don't need to cram all the functionality into a single regex. Chaitanya提出了一个正确的观点:除非您正在玩Regex Golf或完成一项家庭作业,否则您无需将所有功能都塞进一个regex中。 Using a pair of regexes means your url-matcher will be easier to read, and your code in general will be easier to understand. 使用一对正则表达式意味着您的URL匹配器将更易于阅读,并且您的代码通常也将更易于理解。

Something like the following (with an, admittedly, incomplete url matcher) will get you most of the way: 类似于以下内容(带有不完整的url匹配器)将为您提供大部分帮助:

function validate(str) {
 var phrase = /^(\b\S+\b\s?){3,}$/,
   url = /^((http|https|ftp):\/\/)?\w+(\.\w+)+(\/\w+)*(\?(\w+=\w+)(&\w+=\w+)*)?$/;

 return phrase.test(str) && !url.test(str);
}

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

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