简体   繁体   中英

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

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?

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.

You can make two calls to String#replaceAll where the regular expression pattern looks for digits on either side of the 1 and 2 :

public String cleanNumber(String myString) {
    return myString.replaceAll("(?<!\\d)1(?!\\d)", "one")
                   .replaceAll("(?<!\\d)2(?!\\d)", "two");
}

Output:

Happy New Year 2019, it's one January now,two January tommorow

Inspiration taken from: Java Regex to replace string surrounded by non alphanumeric characters

first replace the one-digit 1's and 2's and afterward delete all other numbers

public String cleanNumber( String s ){
  s = s.replaceAll( "(\\D)1(\\D)", "$1one$2" ).replaceAll( "(\\D)2(\\D)", "$1two$2" );
  return( deleteChars.apply( s, "0123456789" ) );
}

String myString = "Happy New Year 2019, it's 1 January now,2 January tommorow";
cleanNumber( myString );  // Happy New Year , it's one January now,two January tommorow

find deleteChars here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM