可以使用正则表达式处理异位词。

huangapple go评论61阅读模式
英文:

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 = &#39;abcadbca&#39;;
console.log(str.match(/(?=.{0,2}b)(?=.{0,2}c)(?=.{0,2}a).{3}/g));

<!-- end snippet -->

This outputs:

[
  &quot;abc&quot;,
  &quot;bca&quot;
]

huangapple
  • 本文由 发表于 2023年3月9日 13:43:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75680821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定