简体   繁体   English

如何从字符串中删除所有非字母数字字符(Java中的小数点除外)

[英]How to remove all non-alphanumeric characters from a string expect decimal point in Java

Having this String with decimal point, I would like to remove all non alphaNumeric expect the decimal point.有了这个带小数点的字符串,我想删除所有非字母数字,除了小数点。

 String toPharse = "the. book - cost 7.55 dollars.";

 String newPharse =  toPharse.replaceAll("[^A-Za-zd.0-9 ]", " ").replaceAll("\\s+", " ");

Currently I get "the. book cost 7.55 dollars."目前我得到"the. book cost 7.55 dollars." ; ;

However I would like to return "the book cost 7.55 dollars" ;但是我想退回"the book cost 7.55 dollars"

You can use:您可以使用:

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 Demo正则表达式演示

RegEx Details:正则表达式详细信息:

  • (?<!\\d) : Previous character is not a digit (?<!\\d) : 前一个字符不是数字
  • \\. : Match a dot : 匹配一个点
  • (?!\\d) : Next character is not a digit (?!\\d) : 下一个字符不是数字
  • | : OR : 或者
  • [^a-zA-Z\\d. ]+ [^a-zA-Z\\d. ]+ : Match 1+ of non-alphanumeric characters that are not space or dot [^a-zA-Z\\d. ]+ :匹配 1+ 个非空格或点的非字母数字字符
  • .replaceAll("\\h{2,}", " ") : is for replacing 2+ whitespaces with a single space .replaceAll("\\h{2,}", " ") :用于用单个空格替换 2+ 个空格

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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