按某些字母拆分字符串同时跳过某些字母

我写了一些代码来用某些字母分割给定的字符串。下面是代码:

let split_by_each_letter_here = "KM";
let re = new RegExp("(?<=[" + split_by_each_letter_here + "])");
let ans = "YGMGPKPDDFLKJJ".split(re);
returns -> [ 'YGM', 'GPK', 'PDDFLK', 'JJ' ]

请注意数组中的每个拆分如何位于“K”或“M”(在 中指定split_by_each_letter_here)。

我想修改此代码,以便每次在我的字符串中直接跟在拆分字母之一(“K”或“M”)之后的“P”时,该字符串不会拆分。例如:

let str = "YGMGPKPDDFLKJJ";
// the array should be ['YGM', 'GPKPDDFLK', 'JJ'];

请注意,由于第一个 'K' 后紧跟一个 'P',因此字符串不会在那里拆分。但是,它确实在第二个 'K' 处分裂,因为在该 'K' 之后没有直接跟随 'P'。

使用 RegEx 是否可以实现我想要的输出?我该怎么做呢?谢谢!

回答

我们可以尝试match如下使用:

var input = "YGMGPKPDDFLKJJ";
var matches = input.match(/.+?(?:[KM](?!P)|$)/g);
console.log(matches);

以下是正则表达式模式的解释:

.+?        match all content up to the nearest
(?:
    [KM]   the letters K or M
    (?!P)  which are NOT immediately followed by P
    |      OR
    $      the end of the input (consume everything until the end)
)


以上是按某些字母拆分字符串同时跳过某些字母的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>