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

WBOY
Release: 2023-03-01 21:48:01
Original
1854 people have browsed it

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

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>
Copy after login
Copy after login

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>
Copy after login
<code>'a,b,c,ab,ac,bc,abc'
</code>
Copy after login

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>
Copy after login
<code>['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']</code>
Copy after login

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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!