简体   繁体   English

Java中的RegEx替换字符串

[英]RegEx in java to replace a String

I've been trying to replace this mathematical function x^2*sqrt(x^3) to this pow(x,2)*Math.sqrt(pow(x,3)) 我一直在尝试将此数学函数x^2*sqrt(x^3)替换为此pow(x,2)*Math.sqrt(pow(x,3))

so this is the regex 所以这是正则表达式

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

it works in ruby, but I can't find a way to do it in java, I tried this method 它可以在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 );

But still doesn´t work, the output is: pow(x, )^2*Math.sqrt(x^3) as I said before it should be pow(x,2)*Math.sqrt(pow(x,3)) . 但仍然不起作用,输出为: pow(x, )^2*Math.sqrt(x^3)就像我之前说的应该是pow(x,2)*Math.sqrt(pow(x,3)) Thank you!! 谢谢!!

As others have commented, regex is not the way to go. 正如其他人所评论的,正则表达式不是要走的路。 You should use a parser. 您应该使用解析器。 But if you want some quick and dirty: 但是,如果您想要一些快速又脏的东西:

From Matcher : 来自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().

So you need to use m.group(1) and m.group(2) . 因此,您需要使用m.group(1)m.group(2) And escape the caret ^ in your regex. 并在您的正则表达式中逃脱插入符号^

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 );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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