How to properly regex nested strings

This question already has an answer here:

  • Regexp to check if parentheses are balanced [duplicate] 3 answers

  • Regexs aren't good parsing things that require state. You could, probably, come up with something that works in some limited scenarios, but not a good regex that could handle a generic case.

    You are better off just parsing your string explicitly. Basically, scan the characters one-by-one, and:

  • if the char is { increase the "nesting counter". If nesting counter==1 , start a new group, and skip to next char;

  • if the char is } , decrease the counter. If nesting_counter == 0 , end the current group, and skip to next char;

  • if nesting_counter>0 append the current char to the group and continue;

  • 链接地址: http://www.djcxy.com/p/59510.html

    上一篇: 正则表达式模式提取大括号之间的字符串并排除大括号

    下一篇: 如何正确地表达嵌套的字符串