时间:2021-07-01 10:21:17 帮助过:3人阅读
var str="abc"; var patt1=/\w/g; document.write(str.match(patt1));
以上代码中,匹配结果为 ['a','b','c']
请问有没有一种正则写法,可以使匹配结果为 ['a','ab','abc','b','bc','c'] ,类似于高中数学的组合
var str="abc"; var patt1=/\w/g; document.write(str.match(patt1));
以上代码中,匹配结果为 ['a','b','c']
请问有没有一种正则写法,可以使匹配结果为 ['a','ab','abc','b','bc','c'] ,类似于高中数学的组合
直接用组合算法吧~
python3
import itertools as itrs
s = "abc"
rslt = ','.join((','.join((''.join(tlp)for tlp in itrs.combinations(s,r)))
for r in range(1,len(s)+1)))
print(rslt)
'a,b,c,ab,ac,bc,abc'
简洁些~
from itertools import chain, combinations as combs
chn_itr = chain.from_iterable
s = "abc"
print([''.join(x)for x in chn_itr(combs(s,r)for r in range(1,len(s)+1))])
['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']
考虑算法实现吧,穷举的js
var str = "abc";
console.log(getStr(str))
function getStr(str) {
var len = str.length;
var i, j;
var res = [];
for (i = 0; i <= len; i++) {
for (j = i + 1; j <= len; j++) {
res.push(str.substr(i, j))
}
}
return res;
}