Reputation: 113
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?
Upvotes: 4
Views: 297
Reputation: 3718
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
Upvotes: 0
Reputation: 29680
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
Upvotes: 1
Reputation: 785058
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.
Upvotes: 4