简体   繁体   中英

about java, String.replaceAll

I've been trying to solve this problem, i did a research a little about the replaceAll method and it seems that it uses a regular expression. But i never heard of any regular expression that contains '.' character. This is the code i've been using:

System.out.println(parsed[1]);
myStatus = parsed[1].replaceAll("...", " ");
System.out.println("new: " + myStatus);
status.setText(myStatus);

Output result is:

old...string new:

If you want to replace the literal String "..." (three dots), either:

  • use replace("...", " ") , which does not use regular expressions
  • use replaceAll("\\\\.{3}", " ") , which is how you specify a literal dot in regex

Unless you need to use replaceAll() (because some implementation you are calling uses it), use replace()

Edited:

Thanks Louis \\\\.{3} is simpler than \\\\.\\\\.\\\\. (doh!)

What your call is actually doing is replacing any group of 3 characters to a space. Thus, the string "old...string" would become 4 spaces. You would require to escape the dots or define a character class quantifier , as they are predefined characters .

Something like

myStatus = parsed[1].replaceAll("[.]{3}", " ");

Note : You can test your regular expressions for Java here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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