匹配字符串之间的多个数字,处理它们并替换

时间:2016-11-15 11:47:04

标签: java regex pattern-matching

我有一个包含多个数字的字符串,必须再次处理并替换为相同的字符串。

例如:

让我说我有:

my name is anusha, I am a noob in Java having reputation: 3647 haha I am just kidding my actual reputation is 0001

现在让我们说我想提取3647并对其进行乘法或除法或加法。我们将3647/100 = 36.47除以原来的数字替换为0001的字符串,并替换为00.01。

结果字符串应为:

my name is anusha, I am a noob in Java having reputation: 36.47 haha I am just kidding my actual reputation is 00.01

感谢您的帮助。我知道这对很多人来说很愚蠢,但我还在学习。

我尝试过:

Pattern intsOnly = Pattern.compile("\\d+");
    Matcher makeMatch = intsOnly.matcher("my name is anusha, I am a noob in Java having reputation: 3647 haha I am just kidding my actual reputation is 0001");
    makeMatch.find();
    String inputInt = makeMatch.group();
    System.out.println(inputInt);

但很明显它只会拿起第一个数字,因为我没有使用循环,我也不确定如何处理这个数字。

4 个答案:

答案 0 :(得分:1)

试试这个:

    final String regex = "\\d+";
    String string = "my name is anusha, I am a noob in Java having reputation: 3647 haha I am just kidding my actual reputation is 0001";
    NumberFormat formatter = new DecimalFormat("00.00");     

    final Pattern pattern = Pattern.compile(regex);
    final Matcher matcher = pattern.matcher(string);

    while (matcher.find()) {
        Float val=new Float(matcher.group(0));
        val=val/100;
        string=string.replace(matcher.group(0),formatter.format(val));
    }
    System.out.println(string);

}

输出:

my name is anusha, I am a noob in Java having reputation: 36.47 haha I am just kidding my actual reputation is 00.01

答案 1 :(得分:0)

  1. 使用空格基础将字符串拆分为字数组
  2. 检查每个单词是否是正确的数字。
  3. 如果它是一个数字设置一个标志并在标志基础上应用你的逻辑 应用逻辑后将单词替换为数组
  4. 按照您的要求将整个数组打印为字符串或连接

答案 2 :(得分:0)

使用PatternMatcher,您可以找到数字的位置。

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(yourStringGoesHere);

while (matcher.find()) {
    System.out.print("Start index: " + matcher.start());
    System.out.print(" End index: " + matcher.end() + " ");
    System.out.println(matcher.group());
}

然后您可以使用substring to add the period

答案 3 :(得分:0)

我发现它here

public double isNumeric(String str){
  String number="";
  Double num=0;
  for (char c : str.toCharArray()){
      if (Character.isDigit(c)){
         number+=c;
      }
  }
  num = Double.parseDouble(number);
  return num; //Then you can do whatever you want with this
}

对不起英文:/