如何比较&将x10变量替换为

时间:2018-03-09 23:43:37

标签: java regex string variables replace

我一直在尝试:

double x10 = 2.4;  
String str = "The value of a variable is x10";  
int c = 0;  
while(c<str.length) #Here digit means a valid Number  
if(str.charAt[c]==digit && str.charAt[c+1]==digit){  
  str.charAt[c] = Double.toString(x10);
}  

期望的输出:

The value of a variable is 2.4

问题:

The problem is that it doesn't seems to be comparing 10 in a String,  
so that it can replace the x10 in the string with the value of variable x10.

有没有其他方法可以达到预期目标?

it works fine with variable x(1-9) but when it exceeds x10 & greater it stucks.  
Didn't found anything relevant to my problem.  

非常鼓励任何帮助!

2 个答案:

答案 0 :(得分:0)

我假设你在C#。您可以使用带有Regex.Replace代表的MatchEvaluator变体。假设您的值在double[] values,并且他们的替换值是一次性的(例如&#34; x1&#34;对应values[0]),您可以:

var ans = Regex.Replace(str, @"x(\d+)", m => values[Convert.ToInt32(m.Groups[1].Value)-1].ToString());

答案 1 :(得分:0)

经过这么多次尝试,才能达到理想的输出效果。我终于找到了解决问题的方法。

    String str = "x12",str2 = "x1";
    if(str2.matches("x[0-9]{1}")==true){

        int var = Integer.parseInt(str.substring(1,2));
        System.out.println(var);

    }else{
        System.out.println("Not Found!");

    }if(str.matches("x[0-9]{2}")==true){

        int var = Integer.parseInt(str.substring(1,2));
        int var2 = Integer.parseInt(str.substring(2,3));
        var = var * 10 + var2;
        System.out.println(var);

    }else{
        System.out.println("Not Found!");
    }