[英]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你需要
split
if it is captured : " If separator is a regular expression that contains capturing parentheses (), matched results are included in the array. "split
后添加到结果数组中: “如果分隔符是包含捕获括号()的正则表达式,则匹配的结果将包含在数组中。 ”.
.
, .*?
.*?
, instead of the greedy .*
. .*
。 Otherwise, the {{.*}}
will match {{
, then any 0 or more chars other than line break chars as many as possible, and then }}
, so all {{...}}
substrings in between {{
and }}
will be put into one match.{{.*}}
将匹配{{
,然后是除换行符之外的任何 0 个或多个字符,然后是}}
,因此{{
和之间的所有{{...}}
子字符串}}
将被放入一场比赛。 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 (?={{|$)
: 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.