我在使用Javascript构建一些正则表达式时遇到了困难。
我需要什么:
我有一个字符串:Woman|{Man|Boy}
或{Girl|Woman}|Man
或Woman|Man
等。
我需要用'|'拆分这个字符串分隔符,但我不希望它在大括号内分割。
字符串和所需结果的示例:
// Expample 1
string: 'Woman|{Man|Boy}'
result: [0] = 'Woman', [1] = '{Man|Boy}'
// Example 2
string '{Woman|Girl}|{Man|Boy}'
result: [0] = '{Woman|Girl}', [1] = '{Man|Boy}'
我无法改变“|”括号内的另一个符号,因为给定的字符串是递归函数的结果。例如,原始字符串可以是
'自然|计算机| {{女孩|女性} | {男孩|男士}}'
答案 0 :(得分:3)
试试这个:
var reg=/\|(?![^{}]+})/g;
示例结果:
var a = 'Woman|{Man|Boy}';
var b = '{Woman|Girl}|{Man|Boy}';
a.split(reg)
["Woman", "{Man|Boy}"]
b.split(reg)
["{Woman|Girl}", "{Man|Boy}"]
您的另一个问题:
"Now I have another, but a bit similar problem. I need to parse all containers from the string. Syntax of the each container is {sometrash}. The problem is that container can contain another containers, but I need to parse only "the most relative" container. mystring.match(/\{+.+?\}+/gi); which I use doesn't work correctly. Could you correct this regex, please? "
你可以使用这个正则表达式:
var reg=/\{[^{}]+\}/g;
示例结果:
var a = 'Nature|Computers|{{Girls|Women}|{Boys|Men}}';
a.match(reg)
["{Girls|Women}", "{Boys|Men}"]
答案 1 :(得分:0)
您可以使用
.match(/[^|]+|\{[^}]*\}/g)
匹配那些。但是,如果你有一个任意深度的嵌套,那么你需要使用一个解析器,[javascript] regex将无法做到这一点。
答案 2 :(得分:-2)
测试一下:
([a-zA-Z0-9]*\|[a-zA-Z0-9]*)|{[a-zA-Z0-9]*\|[a-zA-Z0-9]*}