简体   繁体   English

按不在特定符号之间的符号拆分字符串

[英]Split string by symbol that is not between specific symbols

I want to split a string by "&" only in cases when "&" is not between "<%" and "%>" symbols.我只想在“&”不在“<%”和“%>”符号之间的情况下用“&”分割字符串。 Between that symbols i have special expressions that i want to ignore during the split.在这些符号之间,我有一些特殊的表达式,我想在拆分过程中忽略它们。 Text is considered as special only when it is between two closest "<%" text "%>".仅当文本位于两个最接近的“<%”文本“%>”之间时,文本才被视为特殊文本。 It works like this:它是这样工作的:

<%qwr<%qrw<%tret%>wet%>qwt => only this is scpecial <%tret%>
<%test142%>wqr%>%<%%>qwr%> => only this is <%test142%> and <%%> is special

Examples:例子:

1) my&string=21<%253&124%> <&> && => ['my', 'string=21<%253&124%> <', '> ', '', '']

2) new<%<&%235<%test&gg%>&test&f => ['new<%<', '%235<%test&gg%>', 'test', 'f']

3) a&<%&qwer&>ty%>&af => ['a', '<%&qwer&>ty%>', 'af']

I tried '\\&(?![^<%]*%>)' and (?<!(<%))\\&(?!(%>)) but that works wrong.我试过'\\&(?![^<%]*%>)'(?<!(<%))\\&(?!(%>))但这工作错了。

I would use a workaround.我会使用一种解决方法。

  1. match all <% & %> and replace it with a special char (in my case _ underscore) so the result is <% _ %>匹配所有<% & %>并用特殊字符替换它(在我的例子中是_下划线)所以结果是<% _ %>

  2. now split the string with & char现在用&字符分割字符串

  3. finaly replace the special char _ back to &最后将特殊字符_替换回&

 const mySplit = (mystr) => { const regex = /<%(?!%>).*%>/gm; const matches = mystr.match(regex); const tmpreplace = matches.map(e => e.replace(/&/g,'_')); matches.forEach(e => mystr = mystr.replace(e,tmpreplace)); return mystr.split('&').map(e => e.replace(/_/g,'&')); } console.log(mySplit('my&string=21<%253&124%> <&> &&')); console.log(mySplit('new<%<&%235<%test&gg%>&test&f')); console.log(mySplit('a&<%&qwer&>ty%>&af'));

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

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