首页 > 解决方案 > How to replace a number from a text which is not appended to a string

问题描述

I want to replace the number 123 from the below string, but the challenge I am facing is - everytime I replace it, then the number i.e, 1 from name "Xyz1" also got changed. Below is a sample code which I already tried:

import java.util.*;
import java.lang.*;
import java.io.*;

class NumberToString
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String str = "Hello Xyz1, your id is 123";
        // str = str.replaceAll("[0-9]","idNew");
        // str = str.replaceAll("\\d","idNew");
        // str = str.replaceAll("\\d+","idNew");
        str = str.replaceAll("(?>-?\\d+(?:[\\./]\\d+)?)","idNew");
        System.out.println(str);
    }
}

Output of the above code is: Hello XyzidNew, your id is idNew

But, the output which I need is: Hello Xyz1, your id is idNew

标签: javaregexstring

解决方案


如果您使用正则表达式\d+$,您将获得预期的输出。例子:

public static void main (String[] args) throws java.lang.Exception
{
    String str = "Hello Xyz1, your id is 123";
    str = str.replaceAll("\\d+$","idNew");
    System.out.println(str);
    // Variation without the end of line boundary matcher
    System.out.println("Hello Xyz1, your id is 123.".replaceAll("\\b\\d+(?![0-9])","idNew"));
}

\d+$- 此正则表达式匹配多个数字,后跟行尾。


推荐阅读