简体   繁体   English

用于检查字符串是否具有两个指定单词的正则表达式

[英]Regular expression for check if string has two specified words javascript

I want to create a function that returns true if the string has these two words: "team" and "picture". 我想创建一个函数,如果字符串包含以下两个单词,则返回true:“ team”和“ picture”。

The format of the string will be: "team_user_picture" (example) where "user" can be a different string. 字符串的格式为:“ team_user_picture”(示例),其中“ user”可以是其他字符串。

I tried /team picture/ but this doesn't work for my case. 我尝试了/team picture/但这不适用于我的情况。 How can I do that using a regular expression? 我该如何使用正则表达式呢?

If "team" always comes before "picture", then /team.*picture/ will work. 如果“团队”始终/team.*picture/ “图片”之前,则/team.*picture/将起作用。

Then the function to test that regex would be 然后测试正则表达式的函数将是

function hasKeywords(str) {
    return /team.*picture/.test(str);
}

If you want to test of the string contains both words, regardless of order: 如果要测试的字符串包含两个单词,无论顺序如何:

 var s = 'team_user_picture'; var re = /(team.*picture)|(picture.*team)/; alert(re.test(s)); 

If you want exact validation against your template, use: 如果要对模板进行精确验证,请使用:

/^team_.+_picture$/

This is a job for indexOf. 这是indexOf的工作。 RegEx is inefficient for this task: RegEx对于此任务效率低下:

function hasWords(string) {
    return ~string.indexOf("picture") &&
           ~string.indexOf("team");
}

An even better function would be: 更好的功能是:

function contains(str, ar) {
    return ar.every(function(w) {
        return ~str.indexOf(w);
    });
}

Now you can do: 现在您可以执行以下操作:

contains("team_user_picture", ["team", "picture"])

This will check if the first string has all of the words in the array. 这将检查第一个字符串是否具有数组中的所有单词。


ES6: ES6:

const contains = (s, a) => a.every(w => s.includes(w))

alternatively: 或者:

const contains = (s, a) => a.every(w => s[
    String.prototype.contains ?
    'contains' : 'include'
](w))

If all you want to do is to ensure that both words are in the string, regular expressions are overkill. 如果您要做的只是确保两个单词都在字符串中,则正则表达式会显得过大。 Just use the contains() method like this: 只需使用contains()方法,如下所示:

function check(str) {
    return str.contains("team") && str.contains("picture");
}

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

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