英文:
anagrams can be handled with regexp
问题
这是我的要求
const input = 'abcadbca';
const required = 'bca';
输入包含3个可能的字谜:`abc`,`bca`,`bca`;
所有这些都可以使用 `regexp` 进行选择吗?
我尝试过,但没有结果:
const str = 'abcadbca';
const reg = str.match(/(a|b|c)/g);
console.log(reg);
期望结果:`[a,b,c,][b,c,a],[b,c,a]`;
结果应为 `[a,b,c],[b,c,a]` - 前两个匹配重叠,所以取第一个匹配项。
英文:
here is my requirement
const input = 'abcadbca';
const required = 'bca';
the input contains 3 possibility anagrams as:abc
,bca
,bca
;
is this all can be selected using regexp
?
i tried it, but got not result:
const str = 'abcadbca';
const reg = str.match(/(a|b|c)/g);
console.log(reg);
result expectation: [a,b,c,][b,c,a],[b,c,a]
;
result should be [a,b,c],[b,c,a]
- first 2 match are overlapping so first match is taken for the account.
答案1
得分: 1
const str = 'abcadbca';
console.log(str.match(/(?=.{0,2}b)(?=.{0,2}c)(?=.{0,2}a).{3}/g));
英文:
Since you know in advance the characters that constitute the anagrams you're expecting, as indicated by your required
constant already consisting of characters b
, c
and a
, you can build a regex with each character included in a sub-pattern that expects it in one of the following 3 characters with a lookahead pattern:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const str = 'abcadbca';
console.log(str.match(/(?=.{0,2}b)(?=.{0,2}c)(?=.{0,2}a).{3}/g));
<!-- end snippet -->
This outputs:
[
"abc",
"bca"
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论