简体   繁体   English

通过正则表达式匹配拆分字符串

[英]Split string by regex match

I have this following problem.我有以下问题。 i try to split a string up depending on a regex.我尝试根据正则表达式拆分字符串。 I want to to split it by {{ name }} , {{ age }} and so on.我想用{{ name }}{{ age }}等来分割它。

The expected output should look like this:预期的 output 应如下所示:

["hy my name is: ", "{{ name }}", " and i am ", "{{ age }}", " old"]

My current attempt was this here:我目前的尝试是在这里:

 let str = "hy my name is: {{ name }} and i am {{ age }} old"; let vars = str.split(/({{)(.*)(}})/); console.log(vars);

Whats the correct regex for this task?此任务的正确正则表达式是什么?

You need to你需要

JS fixed demo: JS固定演示:

 let str = "hy my name is: {{ name }} and i am {{ age }} old"; let vars = str.split(/({{.*?}})/); console.log(vars); // => [ "hy my name is: ", "{{ name }}", " and i am ", "{{ age }}", " old"]

Note that { and } are only special if there is a number inside, like {6} .请注意, {}仅在内部有数字时才特殊,例如{6} In {{.*?}} , the curly braces cannot be parsed as limiting quantifiers since there is no number, hence, you may escape { chars in order to prevent any ambiguity.{{.*?}}中,花括号不能被解析为限制量词,因为没有数字,因此,您可以转义{字符以防止任何歧义。

Also, in case you have a match at the start of the string, you will have an empty element in the resulting array, then you need to remove the empty elements:此外,如果您在字符串的开头有匹配项,则结果数组中将有一个空元素,那么您需要删除空元素:

str.split(/({{.*?}})/).filter(Boolean)

Instead of split , you may use this regex with match :而不是split ,您可以将此正则表达式与match一起使用:

/{{.*?}}|.+?(?={{|$)/g

Code:代码:

 let str = "hy my name is: {{ name }} and i am {{ age }} old"; let vars = str.match(/{{.*?}}|.+?(?={{|$)/g); console.log(vars);

RegEx Details:正则表达式详细信息:

  • {{.*?}} : Match a string within {{...}} {{.*?}} :匹配{{...}}中的字符串
  • | : OR : 或者
  • .+? : Match 1+ of any character that satisfies next lookahead condition : 匹配满足下一个前瞻条件的任何字符的 1+
  • (?={{|$) : Positive lookahead condition that makes sure that we have wither {{ or end of line at next position (?={{|$) : 肯定的前瞻条件,确保我们在下一个 position 有枯萎{{或行尾

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM