首页 > 解决方案 > 如何使用看起来像命名组的正则表达式分隔符?

问题描述

我正在拆分一个包含这种形式的子字符串的字符串:

 "<at>foo bar</at>"

使用这个结构:

tokens = command.trim().split( /,\s+|,|\s+|(?=<at>)|(?=<\/at>)/ )

但是,结果是一个数组:

["<at>foo", "bar", "</at>"]

如何修改正则表达式以生成?:

["<at>", "foo", "bar", "</at>"]

提前致谢。

标签: javascriptregex-group

解决方案


您可以匹配零件,而不是使用拆分

<\/?at>|[^<>\s]+

正则表达式演示

const regex = /<\/?at>|[^<>\s]+/g;
console.log(`<at>foo bar</at>`.match(regex));

使用拆分,模式可以是

,\s*|\s+|(?<=<at>)|(?=<\/at>)

const regex = /,\s*|\s+|(?<=<at>)|(?=<\/at>)/g;
console.log(`<at>foo bar</at>`.split(regex))


推荐阅读