Home  >  Article  >  Backend Development  >  javascript - Can regular expressions write glue matches (without using es6's y)?

javascript - Can regular expressions write glue matches (without using es6's y)?

WBOY
WBOYOriginal
2016-12-01 00:56:301846browse

<code>var str="abc"; 
var patt1=/\w/g;
document.write(str.match(patt1));</code>

In the above code, the matching result is ['a','b','c']

Is there a regular writing method that can make the matching result ['a','ab','abc','b','bc','c'], similar to the combination of high school mathematics

Reply content:

<code>var str="abc"; 
var patt1=/\w/g;
document.write(str.match(patt1));</code>

In the above code, the matching result is ['a','b','c']

Is there a regular writing method that can make the matching result ['a','ab','abc','b','bc','c'], similar to the combination of high school mathematics

Just use the combination algorithm~

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>

Keep it simple~

<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>

Consider the algorithm implementation, exhaustive 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>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn