有了这个带小数点的字符串,我想删除除小数点以外的所有非字母数字。
String toPharse = "the. book - cost 7.55 dollars.";
String newPharse = toPharse.replaceAll("[^A-Za-zd.0-9 ]", " ").replaceAll("\s+", " ");
目前我得到"the. book cost 7.55 dollars."
;
但是我想返回"the book cost 7.55 dollars"
;
您可以使用:
String toPharse = "the. book - cost 7.55 dollars.";
toPhrase = toPharse
.replaceAll("(?<!\d)\.(?!\d)|[^a-zA-Z\d. ]+", "")
.replaceAll("\h{2,}", " ");
//=> "the book cost 7.55 dollars"
RegEx演示
RegEx细节:
(?<!\d)
:前一个字符不是数字\.
:匹配点(?!\d)
:下一个字符不是数字|
: or[^a-zA-Z\d. ]+
:匹配1+非空格或点的非字母数字字符.replaceAll("\h{2,}", " ")
:用于将2+空格替换为单个空格