[英]Split string with tags using regular expressions
I would like to split this kind of texts in the following manner: 我想以下列方式分割这类文本:
"string1<%string2%>string3" => [string1, <%string2%>, string3]
"string1<%string2%><%string3%>" => [string1, <%string2%>, <%string3%>]
How can this be done with regular expressions? 如何使用正则表达式完成此操作?
Assuming that <
and >
does not appear in the text outside <%
and %>
, you can use match instead: 假设<
和>
没有出现在<%
和%>
之外的文本中,您可以使用匹配:
"string1<%string2%><%string3%>string4".match(/[^<>]+|<%.*?%>/g)
>>> ["string1", "<%string2%>", "<%string3%>", "string4"]
Here is a way: 这是一种方式:
alert("string1<%string2%><%string3%>".split(/(<%.*?%>)/).filter(Boolean));
The (<%.*?%>)
regex matches <%...%>
-like entities, and captures them so that they are preserved in the resulting array. (<%.*?%>)
正则表达式与<%...%>
类似的实体匹配,并捕获它们以便它们保留在结果数组中。 An alternative regex can also be (<%(?!%>).*?%>)
. 另一种正则表达式也可以是(<%(?!%>).*?%>)
。
With .filter(Boolean)
you will be able to get rid of any empty array elements. 使用.filter(Boolean)
您将能够摆脱任何空数组元素。
In case there are no spaces inside <%...%>
, you can use (<%\\S+%>)
regex. 如果<%...%>
中没有空格,您可以使用(<%\\S+%>)
正则表达式。
You can do: 你可以做:
var re = /(<%[^%]*%>)/;
var m = "string1<%string2%><%string3%>".split(re).filter(Boolean);
//=> ["string1", "<%string2%>", "<%string3%>"]
var m = "string1<%string2%>string3".split(re).filter(Boolean);
//=> ["string1", "<%string2%>", "string3"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.