通过]分割字符串,[ [英] Splitting a string by ],[
问题描述
我有一个如下字符串:
"[a,b,c],[d,e,f],[g,h,i]"
我想知道如何通过<分隔字符串],[
在JavaScript中。 .split(],[)
将删除括号。我想保留它们。
I was wondering how can I separate the string by ],[
in JavaScript. .split("],[")
will remove the brackets. I want to preserve them.
预期输出:
["[a,b,c]","[d,e,f]","[g,h,i]"]
修改:
这是一个更复杂的案例,我在对@Leo的答案的评论中强调了(其中a ],[
-delimited string包含],
):
Here is a more complicated case that I highlighted in a comment on @Leo's answer (wherein a ],[
-delimited string contains ],
):
"[dfs[dfs],dfs],[dfs,df,sdfs]]"
预期产出:
["[dfs[dfs],dfs]","[dfs,df,sdfs]]"]
推荐答案
个人我会
"[dfs[dfs],dfs],[dfs,df,sdfs]]".split("],[");
然后循环到:
- 使用
]
附加第一个字符串。 - 使用<$ c前缀最后一个字符串$ c>[。
- 预设
[
并追加]
介于两者之间的所有字符串。
- Append the first string with a
"]"
. - Prepend the last string with a
"["
. - Prepend a
"["
and append a"]"
to all strings in between.
但是,如果你知道什么样的字符串和你将要收到的角色,你真的想要一个单行方法,你可以尝试下面的黑客。
However, if you know what kind of strings and characters you will be receiving and you reaaaaally want a one-liner approach, you could try the hack below.
替换]的所有实例,[
with ] impossible_string_or_special_unicode [
,然后由impossible_string_or_special_unicode
拆分 - 例如:
Replace all instances of "],["
with "]unlikely_string_or_special_unicode["
, then split by "unlikely_string_or_special_unicode"
- for example:
"[dfs[dfs],dfs],[dfs,df,sdfs]]".replace(/\],\[/g,"]~I_have_a_dream~[").split("~I_have_a_dream~");
警告:不是100%全面证明。如果您的输入字符串具有您用作分隔符的不太可能的字符串,那么它会内爆并且Universe结束。
Warning: Not 100% full-proof. If your input string has the unlikely string you used as a delimiter, then it implodes and the universe comes to an end.
这篇关于通过]分割字符串,[的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!