我想替换两个数字之间或数字和'。之间的所有字符'-'。以char'&'为例。

字符串输入=“ 2.1(-7-11.3)-12.1 * -2.3-.11”
字符串输出=“ 2.1(-7&11.3)-12.1 * -2.3&.11”

我有类似的东西,但我尝试使其更容易。

public void preperString(String input) {

    input=input.replaceAll(" ","");
    input=input.replaceAll(",",".");
    input=input.replaceAll("-","&");
    input=input.replaceAll("\\(&","\\(-");
    input=input.replaceAll("\\[&","\\[-");
    input=input.replaceAll("\\+&","\\+-");
    input=input.replaceAll("\\*&","\\*-");
    input=input.replaceAll("/&","/-");
    input=input.replaceAll("\\^&","\\^-");
    input=input.replaceAll("&&","&-");
    input=input.replaceFirst("^&","-");

    for (String s :input.split("[^.\\-\\d]")) {
        if (!s.equals(""))
        numbers.add(Double.parseDouble(s));
    }

最佳答案

您可以使用正则表达式组一次解决问题,可以使用以下方法:

String input = "2.1(-7-11.3)-12.1*-2.3-.11";
input = input.replaceAll("([\\d.])-([\\d.])", "$1&$2");


输出量

2.1(-7&11.3)-12.1*-2.3&.11




  ([\\d.])-([\\d.])
//        ^------------replace the hyphen(-) that it between
// ^__________^--------two number(\d)
//   ^_^______^_^------or between number(\d) and dot(.)


regex demo

关于java - java String.replaceAll在两个数字之间的字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45535968/

10-11 23:30
查看更多