javascript - 如何使用看起来像命名组的正则表达式分隔符?
问题描述
我正在拆分一个包含这种形式的子字符串的字符串:
"<at>foo bar</at>"
使用这个结构:
tokens = command.trim().split( /,\s+|,|\s+|(?=<at>)|(?=<\/at>)/ )
但是,结果是一个数组:
["<at>foo", "bar", "</at>"]
如何修改正则表达式以生成?:
["<at>", "foo", "bar", "</at>"]
提前致谢。
解决方案
您可以匹配零件,而不是使用拆分
<\/?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))
推荐阅读
- python-3.x - 如何使用热图 seaborn 子图 Python 3.6.0 中的不同间隔值自定义 cmap 中的每种颜色?
- powershell - 使用 Powershell/批处理命令卸载 MS Office 更新(知识库文章)
- windows - 对特定类型的文件运行命令
- python - 无法将表格导入熊猫
- mysql - 为什么 MySQL 在安装过程结束时不给我密码?
- powerbi - 从 Excel 上传到 Power BI 的数据丢失
- flutter - Flutter:防止 FutureBuilder 总是刷新每个更改屏幕
- python - Matplotlib 用双头箭头连接散点图
- c# - 大量的Task.Delay会不会导致性能问题
- node.js - 在 node.js 的生产服务器上获取 502 Bad Gateway