我只想制作
str = "a(bcde(dw)d)e"
到
arr = {"a", "(bcde)", "(dw)", "(d)", "e"}
我可以在str.split()
使用什么regEx?
PS:解释||欢迎提供有用的链接。
示例:
s: "a(bcdefghijkl(mno)p)q" --> [ 'a', '(bcdefghijkl)', '(mno)', '(p)', 'q' ]
s: "abc(cba)ab(bac)c" --> [ 'abc', '(cba)', 'ab', '(bac)', 'c' ]
答案 0 :(得分:2)
str = "a(bcde(dw)d)e"
// replace any `(alpha(` by `(alpha)(`
str1 = str.replace(/\(([^)]+)\(/g, '($1)(');
// replace any `)alpha)` by )(alpha)`
str2 = str1.replace(/\)([^(]+)\)/g, ')($1)');
// prefix any opening parenthesis with #--# (just a character string unlikly to appear in the original string)
str3 = str2.replace(/\(/g, '#--#(');
// prefix any closing parenthesis with #--#
str4 = str3.replace(/\)/g, ')#--#');
// remove any double `#--#`
str5 = str4.replace(/(#--#)+/g, '#--#');
// split by invented character string
arr = str5.split('#--#');
console.log(arr);
str = "a(bcde(dw)d)e"
console.log(str.split(/[()]/));
这看起来有点奇怪,但就像这样。
str是具有split
方法的字符串。这可以将字符串或正则表达式作为参数。字符串将由"
分隔,RegExp由/
分隔。
括号[]
包含一个字符类,表示其中的任何一个字符。然后在里面我们有两个括号()
,它们是我们正在寻找的两个字符。
答案 1 :(得分:2)
使用计数器浏览每个括号:
array = [], c = 0;
'abc(cba)ab(bac)c'.split(/([()])/).filter(Boolean).forEach(e =>
// Increase / decrease counter and push desired values to an array
e == '(' ? c++ : e == ')' ? c-- : c > 0 ? array.push('(' + e + ')') : array.push(e)
);
console.log(array)
答案 2 :(得分:1)
我不认为在分割后不修改数组的值就可以得到你想要的结果。但是如果你想能够根据2个符号(在这种情况下是括号'('和')')拆分字符串,你可以这样做:
var arr = str.split("(").toString().split(")");
它返回一个包含字符串“words”的数组。
我希望我能提供帮助。
答案 3 :(得分:0)
假设所需的输出包括不在字符串中的字符,例如,在嵌套括号的外部部分的子字符串中添加闭括号或打开括号,则需要对各个子字符串进行一些更改。它们是以这种或那种方式提取的。
也许是这样的:
ConfigFactory.load()