0

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

Praveen Kishor
  • 2,413
  • 1
  • 23
  • 28

1 Answers1

1

If you use the regular expression \d+$, you will get the expected output. Example:

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+$ - this regular expression matches multiple digits, followed by the end of the line.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
  • Thanks!! It worked. I just tried and it is working for this scenario, but let say if we add a new string after 123, then in that case whole regex fails. Any suggestions ?? – Praveen Kishor Jul 10 '18 at 06:38
  • @PraveenKishor check the variation in the updated answer which does not use the end of line boundary matcher. – gil.fernandes Jul 10 '18 at 07:07