简体   繁体   English

在一个字符串中查找多个子字符串

[英]Find multiple substrings in a string

I want to check if there are two or more values ​​in a string, regardless of their positions within said string. 我想检查一个字符串中是否有两个或多个值,而不管它们在所述字符串中的位置如何。 For example, if I want a condition of "OR" in regex, I would do so: 例如,如果我要在正则表达式中使用“ OR”条件,则可以这样做:

/(a|b)/.test("a") // true

But what I need is an "AND" ; 但是我需要的是“与” something like this: 像这样的东西:

/(a&b)/.test("a") // false
/(a&b)/.test("b") // false
/(a&b)/.test("a b") // true
/(b&a)/.test("a b") // true
/(a&b&c)/.test("a b") // false
/(a&b&c)/.test("a c b") // true

Obviously this syntax is not correct... 显然,这种语法是不正确的...

These values a , b , c , etc. are pulled from an array. 这些值abc等是从数组中提取的。 I've tried using a combination of eval() and indexOf(a) !== -1 && indexOf(b) !== -1 but that was too slow, which is why I'm turning to regexes. 我尝试使用eval()indexOf(a) !== -1 && indexOf(b) !== -1但这太慢了,这就是为什么我转向正则表达式的原因。

您可以这样做:

/(?=.*a)(?=.*b)/.test("a")

The answer @OmarJackman posted will do what you're asking for. @OmarJackman发布的答案将满足您的要求。 However, it's worth noting that his solution uses lookarounds which require more processing than simpler regexes. 但是,值得注意的是,他的解决方案所使用的环视方法比简单的正则表达式需要更多的处理。 If you're looking for good performance I'd recommend that you just run two separate regexes (test for case a and then for case b ). 如果您正在寻找良好的性能,我建议您只运行两个单独的正则表达式(先对情况a测试,然后对情况b )。 Two simple regexes will run orders of magnitude faster than one complex one, especially as the search text becomes larger. 两个简单的正则表达式的运行速度将比一个复杂的正则表达式快几个数量级,尤其是当搜索文本变大时。

Edit: As noted in the comments, "orders of magnitude" is an unfair exaggeration of the performance impact, but performance should be considered regardless. 编辑:如评论中所述,“数量级”是对性能影响的不公平夸张,但无论如何都应考虑性能。

Since you're matching fixed strings, you could just use: 由于您要匹配固定字符串,因此可以使用:

function matchAll(str, arr)
{
  for (var i=0; i<arr.length; ++i) {
    if (str.indexOf(arr[i]) === -1) {
      return false;
    }
  }
  return true;
}

matchAll('a', ['a']); // true
matchAll('a', ['a', 'b']); // false
matchAll('a b', ['a', 'b']); // true
matchAll('a b c', ['a', 'b']); // true
matchAll('a b', ['a', 'b', 'c']); // false
matchAll('a c b', ['a', 'b', 'c']); // true
matchAll('c a b', ['a', 'b', 'c']); // true

If you're looking for fixed strings, .indexOf() will be faster than regexes. 如果您正在寻找固定的字符串, .indexOf()将比正则表达式更快。

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

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