javascript - 正则表达式能否写出粘连匹配(不使用es6的y)?
程序员文章站
2022-03-08 21:39:16
...
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