JavaScript 围绕大括号拆分

标签 javascript regex string split

我在字符串变量中有一个字符串格式:

"{0} Hello World {1}"

我需要把它分成这样的东西:

"{0}","Hello World","{1}"

根据我的努力,我能得到的最好结果是:

"","0"," Hello World ","1",""

我试过从 Regex Split Around Curly Braces 转换示例 但它没有用,那里的拆分要么删除所有内容,要么保留空格并删除 {}

那么,我的问题与另一篇文章中的问题相同,如何保留大括号 {} 并删除它们前后的空格而不是单词之间的空格?

最佳答案

您可以使用 Split with a regex having capturing group(s) :

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array.

var re = /\s*(\{[0-9]+\})\s*/g;
var splt = "{0} Hello World {1}".split(re).filter(Boolean);
alert(splt);

正则解释:

  • \s* - 任意数量的空格
  • (\{[0-9]+\}) - 匹配的捕获组:
    • \{ - 文字 {
    • [0-9]+ - 1 个或多个数字
    • \} - 文字 }
  • \s* - 任意数量的空格

filter可以帮助摆脱数组中的空元素。

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value or a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

关于JavaScript 围绕大括号拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30576177/

相关文章:

javascript - Node 中的 Map-Reduce

jquery - 删除一个正则表达式中的 2 个(多个)匹配类

c - 为什么 strcpy 在使用大小为 1 的目标字符串时省略源字符串中的第一个字符?

javascript - 为什么我的图像不会出现在 Canvas 上?

javascript - 如何测量溢出内容的div的宽度

javascript - 为什么nodejs不能像浏览器js那样继承

REGEX 在空格之间提取字符串

python - 正则表达式 : Equivalent of\d for any letter in Python?

string - MATLAB:将字符串数组中的第一个字母大写

python - 如何在 Python 中删除反斜杠和附加在反斜杠上的单词?