javascript - 如何使用正则表达式匹配拆分文本

标签 javascript regex

从这种文字开始;

var txt = "hello [a14] world, and [b74] some more [h85], ..."

我期待的结果

var arr = 
  [ "hello "
  , "[a14]"
  , " world, and "
  , "[b74]"
  , " some more "
  , "[h85]"
  , ", ..."
  ] 

到目前为止我已经尝试过,但是掌握正则表达式对我来说仍然很难......

let txt = "hello [a14] world, and [b74] some more [h85], ..."

let arr = txt.match(/(\[(.*?)\])|(.*?)/g)

console.log( arr )
.as-console-wrapper { max-height: 100% !important; top: 0; }

最佳答案

您还可以尝试拆分环视:

var text = "hello [a14] world, and [b74] some more [h85], ...";
var arr = text.split(/(?=\[)|(?<=\])/);
console.log(arr);

这里的逻辑是,只要后面是[,就拆分字符串。或 ] 之前的内容.请注意,lookarounds 的宽度为零,因此模式 (?=\[)|(?<=\])匹配但在拆分时实际上不消耗输入中的任何文本。

关于javascript - 如何使用正则表达式匹配拆分文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66148804/

相关文章:

javascript - 正在删除一条记录,但为什么 .setState 不起作用?

javascript - 使用 Google Geocoding API 将命名实体识别标记文件链接到 Google map

javascript - 内容安全策略 “Refused to execute inline event handler” 错误

java - 模式中的规范等价

regex - 如何在 postgreSQL 中正确比较正则表达式?

python - 用于匹配第三、第四、第五...单词的正则表达式

javascript - 正则表达式/Javascript 帮助 - 搜索 URL 术语解析

javascript - 在javascript中将UTC字符串转换为纪元时间

javascript - 如何使用createElement和appendChild防止页面重新加载时div重新排序?

javascript - jQuerys $.trim(),错误还是写得不好?