Java Regex recursive match

喜欢而已 提交于 2021-02-19 07:34:07

问题


I have a string like this:

IF(expr1,text1,IF(expr2,text2,IF(expr3,text3,text4)))

I need to process IF(expr3,text3,text4))) so the above become

 IF(expr1,text1,IF(expr2,text2,new_text))

I need to keep doing this until I have

 IF(expr1,text1,new_text3)

My pattern string "IF\\(.*?,.*?,.*?\\)" will match the whole thing. Not the IF(expr3,text3,text4))).

Java code:

String val = "IF(expr1,text1,IF(expr2,text2,IF(expr3,text3,text4)))";
String regx = "IF\\(.*?,.*?,.*?\\)";  
Pattern patt1 = Pattern.compile(regx);
Matcher m2 = patt1.matcher(val);
while (m2.find()) { 
    String val0 = m2.group();
    System.out.println( val0 ); 
}  

回答1:


One way to accomplish this would be to create a method which locates and returns any inner IF statement using regex. Within this method you would call itself each time another inner IF statement is found by your regex match. Here is a very simplified snippet only to demonstrate the concept. This essentially accomplishes recursive regex matching, however needs to be done manually due to lack of support for recursive regex in standard Java. I improvised here since I don't have a compiler to test this on. You will need to modify your matching regex to locate first inner IF statement however. Perhaps a regex expression like this ^IF\(.*?,.*?,(IF\(.*\))\) would work?

String val = 'IF(expr1,text1,IF(expr2,text2,IF(expr3,text3,text4)))';

String mostInnerIfStatement = getInnerIfStatement(val);

// no inner IF statement found
if(mostInnerIfStatement == null) {
    // handle scenario where IF statement has no inner IF statements
}

String getInnerIfStatement(String val) {
    String regx = '^IF\\(.*?,.*?,(IF\\(.*\\))\\)';  
    Pattern patt1 = Pattern.compile(regx);
    Matcher m2 = patt1.matcher(val);

    // initialize to value passed in
    String nextInnerIfStatement = val;

    // test if match found
    if(m2.find()) {
        // call self if another match found
        String result = getInnerIfStatement(m2.group());

        // if result is null then no more inner IF statements found so do not set nextInnerIfStatement
        if(result != null) {
            nextInnerIfStatement = result;
        }
    }

    return nextInnerIfStatement;
}


来源:https://stackoverflow.com/questions/37890382/java-regex-recursive-match

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!