正则表达式删除字符串中的所有数字,除了特定的单词

时间:2018-03-08 08:44:24

标签: java regex string

我试图实现一个正则表达式,它将从字符串中删除所有数字字符,但某些特定单词除外。例如,假设我有一个字符串str1,如下所示:

    String str1 = "noDriver vehicle1 0.0 5 eric clarks 109.9819741964403 119.9819741964403 229.9639483928806 ";
  //what i would like is something like this , 
  //which will remove all words, integers,float in final it will have to return only "vehicle1"
  String str2= str1.replace(floats,"").replace(words,"").replace(integers,"");

最后应该只返回vehicle1(包含字符串和整数),有人可以帮忙吗?

尝试

str2=str1.replaceAll("\\s+"," ").replaceAll("\\d","")

1 个答案:

答案 0 :(得分:0)

您要删除:

  • 浮动\d+\.\d+
  • 整数\d+
  • 单词[a-zA-Z]+

所以你可以写:

String str1 = "noDriver vehicle1 0.0 5 eric clarks 109.9819741964403 119.9819741964403 229.9639483928806 ";
String str2 = str1.replaceAll("\\b(\\d+\\.\\d+|\\d+|[a-zA-Z]+)\\b", "");

System.out.println(str2);
// Output: "vehicle1"