问题
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