用Java正则表达式递归替换? [英] Recursive replace with Java regular expression?

查看:65
本文介绍了用Java正则表达式递归替换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以用 (10)%(5) 替换 ABC(10,5) 使用:

I can replace ABC(10,5) with (10)%(5) using:

replaceAll("ABC\\(([^,]*)\\,([^,]*)\\)", "($1)%($2)")

但我无法弄清楚如何为 ABC(ABC(20,2),5)ABC(ABC(30,2),3+2).

but I'm unable to figure out how to do it for ABC(ABC(20,2),5) or ABC(ABC(30,2),3+2).

如果我能够转换为 ((20)%(2))%5 我怎样才能转换回 ABC(ABC(20,2),5)?

If I'm able to convert to ((20)%(2))%5 how can I convert back to ABC(ABC(20,2),5)?

谢谢,j

推荐答案

我来回答第一个问题.我无法在单个 replaceAll 中完成任务.我认为它甚至无法实现.但是,如果我使用循环,那么这应该为您完成工作:

I am going to answer about the first question. I was not able to do the task in a single replaceAll. I don't think it is even achievable. However if I use loop then this should do the work for you:

    String termString = "([0-9+\\-*/()%]*)";
    String pattern = "ABC\\(" + termString + "\\," + termString + "\\)";
    String [] strings = {"ABC(10,5)", "ABC(ABC(20,2),5)", "ABC(ABC(30,2),3+2)"};
    for (String str : strings) {
        while (true) {
            String replaced = str.replaceAll(pattern, "($1)%($2)");
            if (replaced.equals(str)) {
                break;
            }
            str = replaced;
        }
        System.out.println(str);
    }

我假设您正在为数字表达式编写解析器,因此术语 termString = "([0-9+\\-*/()%]*)" 的定义.它输出这个:

I am assuming you are writing parser for numeric expressions, thus the definition of term termString = "([0-9+\\-*/()%]*)". It outputs this:

(10)%(5)
((20)%(2))%(5)
((30)%(2))%(3+2)

EDIT 根据 OP 请求,我添加了用于解码字符串的代码.它比前向场景更棘手:

EDIT As per the OP request I add the code for decoding the strings. It is a bit more hacky than the forward scenario:

    String [] encoded = {"(10)%(5)", "((20)%(2))%(5)", "((30)%(2))%(3+2)"};
    String decodeTerm = "([0-9+\\-*ABC\\[\\],]*)";
    String decodePattern = "\\(" + decodeTerm + "\\)%\\(" + decodeTerm + "\\)";
    for (String str : encoded) {
        while (true) {
            String replaced = str.replaceAll(decodePattern, "ABC[$1,$2]");
            if (replaced.equals(str)) {
                break;
            }
            str = replaced;
        }
        str = str.replaceAll("\\[", "(");
        str = str.replaceAll("\\]", ")");
        System.out.println(str);
    }

输出为:

ABC(10,5)
ABC(ABC(20,2),5)
ABC(ABC(30,2),3+2)

这篇关于用Java正则表达式递归替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆