Rumah > Artikel > pembangunan bahagian belakang > javascript - 正则表达式能否写出粘连匹配(不使用es6的y)?
<code>var str="abc"; var patt1=/\w/g; document.write(str.match(patt1));</code>
以上代码中,匹配结果为 ['a','b','c']
请问有没有一种正则写法,可以使匹配结果为 ['a','ab','abc','b','bc','c'] ,类似于高中数学的组合
<code>var str="abc"; var patt1=/\w/g; document.write(str.match(patt1));</code>
以上代码中,匹配结果为 ['a','b','c']
请问有没有一种正则写法,可以使匹配结果为 ['a','ab','abc','b','bc','c'] ,类似于高中数学的组合
直接用组合算法吧~
python3
<code class="python">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)</code>
<code>'a,b,c,ab,ac,bc,abc' </code>
简洁些~
<code class="python">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))])</code>
<code>['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']</code>
考虑算法实现吧,穷举的js
<code>var str = "abc"; console.log(getStr(str)) function getStr(str) { var len = str.length; var i, j; var res = []; for (i = 0; i </code>