3 回答
TA贡献1851条经验 获得超3个赞
replaceAll您可以按以下顺序使用:
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
此外,在替换时使用字边界1并2避免将这些数字作为其他数字的一部分进行匹配也很重要。
TA贡献1833条经验 获得超4个赞
您可以对正则表达式模式在andString#replaceAll
两侧查找数字的位置进行两次调用:1
2
public String cleanNumber(String myString) { return myString.replaceAll("(?<!\\d)1(?!\\d)", "one") .replaceAll("(?<!\\d)2(?!\\d)", "two"); }
输出:
Happy New Year 2019, it's one January now,two January tommorow
TA贡献1876条经验 获得超5个赞
首先替换一位数的 1 和 2,然后删除所有其他数字
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
添加回答
举报