【问题标题】:RegEx in java to replace a Stringjava中的RegEx替换字符串
【发布时间】:2013-05-11 22:19:56
【问题描述】:

我一直在尝试将这个数学函数 x^2*sqrt(x^3) 替换为这个 pow(x,2)*Math.sqrt(pow(x,3))

所以这是正则表达式

/([0-9a-zA-Z\.\(\)]*)^([0-9a-zA-Z\.\(\)]*)/ pow(\1,\2)

它在 ruby​​ 中有效,但我找不到在 java 中的方法,我尝试了这个方法

String function=  "x^2*sqrt(x^3)";

  Pattern p = Pattern.compile("([a-z0-9]*)^([a-z0-9]*)");
  Matcher m = p.matcher(function);

  String out = function;

  if(m.find())
  {
      System.out.println("GRUPO 0:" + m.group(0));
      System.out.println("GRUPO 1:" + m.group(1));
      out = m.replaceFirst("pow(" + m.group(0) + ", " + m.group(1) + ')');
  }
      String funcformat = out;
      funcformat = funcformat.replaceAll("sqrt\\(([^)]*)\\)", "Math.sqrt($1)"); 

      System.out.println("Return Value :"+ funcion );
      System.out.print("Return Value :"+ funcformat );

但仍然不起作用,输出是:pow(x, )^2*Math.sqrt(x^3),正如我之前所说的,它应该是 pow(x,2)*Math.sqrt(pow(x,3))。 谢谢!!

【问题讨论】:

  • 对于一般的数学表达式,写一个解析器来做。单独的 Java 正则表达式无法处理嵌套括号。对于这种特定情况,可以使用正则表达式,但我不推荐它。
  • 同意正则表达式不是要走的路。那里有许多现有的解析器。你不必自己动手。
  • 请注意您的输入字符串很奇怪:"x^2*sqrt(3x)" 你的意思是x^3 吗?
  • @nhahtdh 是的,已经更正了。

标签: java regex string math replace


【解决方案1】:

正如其他人评论的那样,正则表达式不是要走的路。您应该使用解析器。但是,如果您想要一些快速而肮脏的东西:

来自Matcher

Capturing groups are indexed from left to right, starting at one. 
Group zero denotes the entire pattern, so the expression m.group(0)
is equivalent to m.group().

所以你需要使用m.group(1)m.group(2)。并在您的正则表达式中转义插入符号 ^

import java.util.regex.*;

public class Replace {
    public static void main(String[] args) {
        String function=  "x^2*sqrt(3x)";
        Pattern p = Pattern.compile("([a-z0-9]*)\\^([0-9]*)");
        Matcher m = p.matcher(function);
        String out = function;

        if (m.find())   {
            System.out.println("GRUPO 0:" + m.group(1));
            System.out.println("GRUPO 1:" + m.group(2));
            out = m.replaceFirst("pow(" + m.group(1) + ", " + m.group(2) + ')');
        }
        String funcformat = out;
        funcformat = funcformat.replaceAll("sqrt\\(([a-z0-9]*)\\^([0-9]*)]*\\)", "Math.sqrt(pow($1, $2))"); 
        System.out.println("Return Value :"+ function );
        System.out.print("Return Value :"+ funcformat );
    }
}

【讨论】:

  • @nhahtdh 你是对的。我已经修复了代码。我认为它现在可以工作了……但正如我所说,他应该使用解析器。
  • 其实可以让它适用于更多的测试用例。目前它只适用于x^3*sqrt(x^4),当你交换sqrt(x^4)*x^3时会失败。想法是替换所有name^power,然后用Math.sqrt( 替换sqrt(。它仍然不够通用,但至少比当前代码生存得更好。
  • @nhahtdh 很好,我没想到...绝对不是正则表达式。
  • 这对于询问查询等所有问题并不通用。你必须给出一个通用的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 2014-04-19
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2015-12-23
相关资源
最近更新 更多