在javascript中将字符串拆分为匹配和不匹配的组 [英] Splitting string into matching and non-matching groups in javascript

查看:34
本文介绍了在javascript中将字符串拆分为匹配和不匹配的组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串拆分为匹配正则表达式和不匹配正则表达式的字符串数组:

I am trying to split the string into an array of strings those matching a regular expression and those that don't:

string = "Lazy {{some_animal}} jumps over.."
# do some magic with regex /({{\s?[\w]+\s?}})/g and its negation
array = ["Lazy ", "{{some_animal}}", " jumps over.."]

在 javascript 中执行此操作的最佳方式?

Best performant way to do that in javascript?

推荐答案

可以使用 字符串匹配为此

下面的正则表达式只匹配任何不是胡须的东西,可以选择被胡须包围.

The regex below simply matches anything that's not a mustach, optionally surrounded by mustaches.

示例片段:

var str = "Lazy {{some_animal}} jumps over..";

const pattern = /\{*[^{}]+\}*/g;

var array = str.match(pattern);

console.log(str);
console.log(pattern);
console.log(array);

但为了更精确,正则表达式模式变得有点复杂.
下面的正则表达式匹配:

But to make it more precise, the regex pattern becomes a bit more complicated.
The regex below matches:

  1. 你想要什么"
    (每边2个胡须之间的一个词)
  2. 或你不想要的,然后是你想要的"
    (使用延迟匹配和正向预测)
  3. 或剩下的"

var str = "Lazy {{some_animal}} jumps over..";

const pattern = /\{\{\w+\}\}|.+?(?=\{\{\w+\}\})|.+/g;

var array = str.match(pattern);

console.log(str);
console.log(pattern);
console.log(array);

最后但并非最不重要的是,邪恶的 SM 方法.
在同一个正则表达式上拆分 AND 匹配.并将它们连接成一个数组.
这种方法的缺点是不保留顺序.

And last but not least, the evil SM method.
Split AND Match on the same regex. And concatinate them into a single array.
The downside of this method is that the order is not preserved.

var str = "Lazy {{some_animal}} jumps over..";

const pattern = /\{\{\w+\}\}/g;

var what_you_want = str.match(pattern);
var what_you_dont_want = str.split(pattern);

var array = what_you_want.concat(what_you_dont_want);

console.log(str);
console.log(pattern);
console.log(array);

这篇关于在javascript中将字符串拆分为匹配和不匹配的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆