英文:
How to split strings with regex like {{(all spaces)variableValue(all spaces)}}
问题
需要根据此正则表达式拆分字符串,但我无法编写它。
介绍性语句:
{{ text1 }} 123 {{text1}}{{text1}} {{ text1}}134
变量中的文本:
const a = text1;
拆分结果:
["{{text1}}"," 123 ","{{text1}}","{{text1}}"," ","{{text1}}","134"]
还要记住,text1 这个词只是一个可以更改的变量的值。
我尝试通过新的正则表达式在那里插入变量的值来做到这一点,但我仍然无法进行正常拆分。
英文:
It is necessary to split the strings according to such a regex, but I cannot compose it.
Introductory line:
{{ text1 }} 123 {{text1}}{{text1}} {{ text1}}134
Text in a variable:
const a = text1;
Split result:
["{{text1}}"," 123 ","{{text1}}","{{text1}}"," ","{{text1}}","134"]
Also, keep in mind that the word text1 is just the value of a variable that can change.
I tried to do it through new Regexp to insert the value of the variable there, but I still couldn’t do a normal split.
答案1
得分: 1
这个部分的翻译如下:
这个部分不关心括号内的单词。
如果你真的想要在第4个元素中保留空格,我们需要测试在修剪之前是否有一个空格。
https://regex101.com/r/RMEeRd/1
const input = `{{ text1 }} 123 {{text1}}{{text1}} {{ text1}}134`;
const regex = /\{\{\s*([^}]+)\s*\}\}|([^{}]+)/g;
const matches = [...input.matchAll(regex)].map(match => match[0].trim());
console.log(matches)
英文:
This one does not care what word is in the brackets
If you really want the space in element 4, we will need to test for one space before trimming
https://regex101.com/r/RMEeRd/1
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const input = `{{ text1 }} 123 {{text1}}{{text1}} {{ text1}}134`;
const regex = /\{\{\s*([^}]+)\s*\}\}|([^{}]+)/g;
const matches = [...input.matchAll(regex)].map(match => match[0].trim());
console.log(matches)
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论