使用java仅从字符串中删除嵌套的花括号
我有一个任务,消息中有嵌套的花括号。我的动机是只删除最里面的花括号,消息的其余部分保持不变。字符串消息的示例如下:使用java仅从字符串中删除嵌套的花括号,java,regex,parsing,Java,Regex,Parsing,我有一个任务,消息中有嵌套的花括号。我的动机是只删除最里面的花括号,消息的其余部分保持不变。字符串消息的示例如下: enter code here Input : {4:{CLIENT ACCOUNT} :-} Output: {4: CLIENT ACCOUNT :-} 所以基本上我们需要确保去掉最里面的花括号,剩下的内容保持不变。怎么做 我能够使用以下伪代码删除一级大括号: enter code here String str ="{CLIENT ACC
enter code here Input : {4:{CLIENT ACCOUNT} :-}
Output: {4: CLIENT ACCOUNT :-}
所以基本上我们需要确保去掉最里面的花括号,剩下的内容保持不变。怎么做
我能够使用以下伪代码删除一级大括号:
enter code here
String str ="{CLIENT ACCOUNT}";
String regex = "(\\{|\\})";
str = str.replaceAll(regex, "");
System.out.println("Formatted String is--"+str);
但是我一直在考虑如何使用正则表达式来忽略第一级花括号。非常感谢您的帮助。我不知道如何使用java正则表达式,但您可以这样做:
String str = "someContent";
String newStr = "";
int level = 0;
for (int i = 0; i < str.length(); ++i){
if (str.charAt(i) == '{'){
if (level == 0) //check before incrementing
newStr += "{";
level++;
} else if (str.charAt(i) == '}'){
level--;
if (level == 0) //check after incrementing
newStr += "}";
} else {
newStr += str.charAt(i);
}
}
return newStr;
String str=“someContent”;
字符串newStr=“”;
智力水平=0;
对于(int i=0;i
基本上,您可以单步遍历字符串中的每个字符,并记住您已经看到了多少个“{”和“}”。只有当你的净计数为零(或最外层的括号)时,你才能打印出来。这不是最漂亮的答案。它不适用于深度嵌套的花括号,但适用于多组嵌套的花括号
(\{[^}]+?|\G[^{]*)\{([^}]+)\}
$1 $2
在上面的演示中,您可以看到当我们有一组多嵌套的花括号时所导致的错误。这是因为我们假设内容将是[^}]+
,或者除了结束括号以外的任何内容。下面是一个扩展的解释:
( (?# start capture)
\{ (?# match { literally)
[^}]+? (?# lazily match 1+ non-})
| (?# OR)
\G (?# start back from last match, still in a curly bracket)
[^{]* (?# match 0+ non-{ characters)
) (?# end capture)
\{ (?# match { literally)
( (?# start capture)
[^}]+ (?# match 1+ non-} characters)
) (?# end capture)
\} (?# match } literally)
thx用于详细解释sam。只有两个嵌套级别。不超过这个级别。在这种情况下如何进行。我尝试使用您的答案,但它没有按预期运行。通过“两个嵌套级别”您指的是我的示例中的
{FOO{OOPS}BAR}
{1:{CLIENT ACCOUNT},2:{FOO{OOPS}BAR},3:{TEST TEST}
?如果是这样,您期望结果是什么..请更新OP:)Sam,通过两级嵌套我的意思是:如果输入是:{4:{CLIENT ACCOUNT}:-},那么输出是:{4:CLIENT ACCOUNT:-}。请检查我的最新问题。它清楚地提到了。嗨,Harrison,你的java代码在集成到程序中时似乎运行得很好。非常感谢。我在过去几天一直在与regex进行斗争,但没有结果。我将接受你的答案。干杯
( (?# start capture)
\{ (?# match { literally)
[^}]+? (?# lazily match 1+ non-})
| (?# OR)
\G (?# start back from last match, still in a curly bracket)
[^{]* (?# match 0+ non-{ characters)
) (?# end capture)
\{ (?# match { literally)
( (?# start capture)
[^}]+ (?# match 1+ non-} characters)
) (?# end capture)
\} (?# match } literally)