最后一个元素的模式

时间:2016-11-12 18:23:22

标签: java android regex recursion

所以我最近写了一段像这样的正则表达式:

replaceInputWithLatex("sinus(?<formula>.*?)moveout",
    "\\\\sin(${formula})");

replaceInputWithLatex("sinus(?<formula>.+)",
    "\\\\sin" + changeColorOfString("Red", "(") + "${formula}" + changeColorOfString("Red", ")"));

replaceInputWithLatex("sinus",
    "\\\\sin" + noInputBox);

这里有replaceInputWithLatex函数:

private static void replaceInputWithLatex(String pattern, String latexOutput{
    regexPattern = Pattern.compile(pattern);
    regexMatcher = regexPattern.matcher(mathFormula);

    while(regexMatcher.find()){
        Log.d("FOUND", regexMatcher.group());

        mathFormula = regexMatcher.replaceAll(latexOutput);
        replaceInputWithLatex(pattern, latexOutput);
    }
}

让我说我输入一个字符串:&#34; sinus1 + sinus2x + 3moveout&#34;。

我希望第一场比赛拿下这个字符串:&#34; sinus2x + 3moveout&#34;。并替换它。并且在下一次迭代中匹配&#34; sinus1 +(已经转换)&#34;。

然而,到目前为止,它首先需要整个字符串。这是&#34; FOUND&#34;日志:

11-12 19:26:40.750 30244-30244/com.example.user.signum D/FOUND: sinus1+sinus2x+3moveout
11-12 19:26:40.750 30244-30244/com.example.user.signum D/FOUND: sinus2x+3

Latex输出看起来像这样(我希望两个外括号都是红色的 - 与现在的顺序相反):

enter image description here

我应该使用什么样的模式? (我一直在尝试递归方法,但我还没有提出解决方案)

1 个答案:

答案 0 :(得分:0)

我在JavaScript中嘲笑了一个工作示例。

基本上,我们一直使用相同的正则表达式来输入输入。我们标记了尾部,我们已经处理了一些特殊字符,然后处理左边的下一个,依此类推。当标记覆盖整个字符串时,我们就完成了。

&#13;
&#13;
console.clear();
var input = "sinus1+sinus2x+3moveout";
do {
  console.log(input);
  input = input.replace(/(sinus\dx?\+)?(?:\d?moveout|(<<handled>>))$/, function(m,lead){
    return lead ? "<<handled>>" : "{{all done}}"
  });
} while (input.indexOf("<<") !== -1);
console.log(input);
&#13;
&#13;
&#13;

它有点伪代码,但我希望这会给你一些有用的想法。