简体   繁体   中英

Java regex pattern overmatching(Pattern matches one sequence instead of two)

When I write: "integralfrom1to10ofx^2)+integralfrom1to10ofx^3)",

I expect my regex:

// INTEGRAL BASIC
Pattern integralFinalPattern = Pattern.compile("integralfrom(.*)to(.*)of(.*)\\)");
Matcher integralFinalMatcher = integralFinalPattern.matcher(regexDedicatedString);
if(integralFinalMatcher.find()){
    String integral_user_input = integralFinalMatcher.group(0);
    String integral_lower_index = integralFinalMatcher.group(1);
    String integral_upper_index = integralFinalMatcher.group(2);
    String integral_formula = integralFinalMatcher.group(3);
    String ultimateLatexIntegral = "(\\int_{"+ integral_lower_index
                +"}^{"+ integral_upper_index +"} " + integral_formula + ")";

    mathFormula = mathFormula.replace(integral_user_input, ultimateLatexIntegral);
}

to match these two strings separately, but for now it would interpret it as one. And in result of it I'd get the following latex SVG: 错误的正则表达式解释的示例图片

I would like to have output with two separate integrals, like here: 所需的正则表达式解释 How can I achieve this with regex?

Obviously, I seek for an idea that would make it work for more than two pieces.

You're doing a lot of work that the Matcher class can do for you. Check it out:

Pattern p = Pattern.compile("integralfrom(?<upper>.*?)to(?<lower>.*?)of(?<formula>.*?)\\)");
Matcher m = p.matcher(subject);
result = m.replaceAll("\\\\int_{${upper}}^{${lower}} (${formula})");

With an input of "integralfrom1to10ofx^2)+integralfrom1to10ofx^3)" , the result is:

\int_{1}^{10} (x^2)+\int_{1}^{10} (x^3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM