How to split strings with regex like {{(all spaces)variableValue(all spaces)}}

huangapple go评论74阅读模式
英文:

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 =&gt; match[0].trim());
console.log(matches)

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月14日 02:18:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76244269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定