<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 <= len; i++) { for (j = i + 1; j <= len; j++) { res.push(str.substr(i, j)) } } return res; }</code>