1

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 ); 
}  
2
  • Where in the code do you add new and 3? What are the specifications? Commented Jun 17, 2016 at 21:39
  • Regex is not the tool for recursion. What you have looks like a language of sorts and you might want to consider something like ANTLR, or build your own parser. Commented Jun 18, 2016 at 16:40

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.