How do you check if a string contains ALL strings from another array?

2016-04-25 15:35:59 +08:00
 CupTools

Say I have some strings,

var string1 = "hey this is jack and michael";
var string2 = "hey this is jack and jenny";

And I have an array of strings:

var arr = ['jack', jenny'];

How do you write a function so that:

fn(string2, arr); // true
fn(string1, arr); // false

Kind of like String.indexOf() or regex with a|b|c, but no individually.

2370 次点击
所在节点    JavaScript
10 条回复
ershisi
2016-04-25 15:49:37 +08:00
虽然不知道为什么要用英文。你的数组缺少一个闭合。
另外最简单的办法,如果你的字符串都是以空格分隔的。那就把第一个 string 参数分割成数组。然后再去判断。用不着正则的感觉。。。
Magic347
2016-04-25 15:53:25 +08:00
python 版:

def fn(str, arr):
____return all(x in str for x in arr)
CupTools
2016-04-25 16:11:05 +08:00
@ershisi 中文太差 表达不清
spance
2016-04-25 16:27:52 +08:00
这个其实就是多模式匹配,比较好的方法是使用 W-M 或者 A-C 算法可以做到 O(m+n),或者没啥要求或者数量较小就像最后那个 for 里面逐个查找也可以。
jyyyxy
2016-04-25 17:13:18 +08:00
java 版 BiPredicate<String, List<String>> fun = (str, arr) -> arr.stream().allMatch(str::contains);
xjp
2016-04-25 19:11:33 +08:00
arr.every((s) => string1.contains(s));
murmur
2016-04-25 19:16:48 +08:00
AC 自动机 应该有 java 版的
zhujinliang
2016-04-25 19:25:28 +08:00
javascript:

function containsAll(haystack, needles) {
return !!haystack.match(new RegExp('('+needles.join('|')+')'));
}
pollow
2016-04-25 19:48:59 +08:00
我还以为进来能看到有人讨论 AC 自动机,没想到一群写循环的……
wsdjeg
2016-04-25 22:21:10 +08:00
VIML

let s:str1 = "hey this is jack and michael"
let s:str2 = "hey this is jack and jenny"
let s:list = ['jack', 'jenny']

fu! s:checkstr(str,list)
if 0 < index(split(a:str,' '),a:list[0]) && index(split(a:str,' '),a:list[0]) < index(split(a:str,' '),a:list[1])
return "true"
else
return "false"
endif
endf

echom s:checkstr(s:str1,s:list)
echom s:checkstr(s:str2,s:list)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/274263

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX