How to remove all number in string except "1" and "2"?

Ruddy Cahyanto :

I want to delete all number in a String except number 1 and 2 that stand alone. And then I want to replace 1 with one and 2 with two.

For example, the input and output that I expect are as follows:

String myString = "Happy New Year 2019, it's 1 January now,2 January tommorow";

Expected output:

myString = "Happy New Year, it's one January now,two January tommorow";

So, 1 and 2 in 2019 are deleted, but 1 and 2 that stand alone are replaced by one and two.

I've tried using regex, but all numbers were erased. Here is my code:

public String cleanNumber(String myString){
    String myPatternEnd = "([0-9]+)(\\s|$)";
    String myPatternBegin = "(^|\\s)([0-9]+)";
    myString = myString.replaceAll(myPatternBegin, "");
    myString = myString.replaceAll(myPatternEnd, "");
    return myString;
}

I also tried to replace with this regex [1] and [2] but the 2019 becomes two0one9.

I have no idea how to change this 1 and 2 that stand alone. Any recommendations?

anubhava :

You may use replaceAll in this order:

myString = myString
          .replaceAll("\\b1\\b", "one") // replace 1 by one
          .replaceAll("\\b2\\b", "two") // replace 2 by two
          .replaceAll("\\s*\\d+", "");  // remove all digits

//=> Happy New Year, it's one January now,two January tommorow

Also it is important to use word boundaries while replacing 1 and 2 to avoid matching these digits as part of some other number.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=305726&siteId=1