我有一个字符串,其中包含格式为{{******}}
的多个子字符串,其中*****
可能是一些事情。我正在尝试拆分我的字符串,以便生成的数组包含这些子字符串之前和之后的子字符串,以及完整的子字符串本身。
我创建了一个可在此处运行的正则表达式:https://regex101.com/r/I65QQD/1/
当我呼叫str.split(...)
以包含完整匹配时,我想要结果数组,如上面的链接所示。现在它正在返回子组,所以我的数组看起来很奇怪:
let body = "Hello, thanks for your interest in the Melrose Swivel Stool. Although it comes in 2 different wood finishes, there aren't any options for the upholstery fabric. {{youtube:hyYnAioXOqQ}}\n Some similar stools in different finishes are below for your review. I hope this is helpful to you!\n\n{{attachment:2572795}}\n\n{{attachment:2572796}}\n\n{{attachment:2572797}}\n\n{{attachment:2572798}}\n";
let bodyComponents = body.split(/{{attachment:([\d]+)}}|{{(YOUTUBE|VIMEO):([\d\w]+)}}/i);
console.log(bodyComponents);
有没有办法让结果数组包含完整匹配而不是子组?所以它看起来像这样:
[
"Hello, thanks for your interest in the Melrose Swivel Stool. Although it comes in 2 different wood finishes, there aren't any options for the upholstery fabric. ",
"{{youtube:hyYnAioXOqQ}}",
...
]
由于
答案 0 :(得分:1)
您需要删除不必要的捕获括号并将您拥有的替换组转换为非捕获括号:
/({{attachment:\d+}}|{{(?:YOUTUBE|VIMEO):\w+}})/
请注意[\d\w]
= \w
和[\d]
= \d
。
请注意,整个模式都包含一个单个捕获组。 ({{attachment:\d+}}
没有捕获组\d+
,(?:YOUTUBE|VIMEO)
现在是非捕获组(因此它的值不会在结果数组中显示为单独的项)和{{1变成([\d\w]+)
(\w+
是多余的,因为\d
也匹配数字。)
\w