简体   繁体   中英

Replace numbers inside a string using Regex

I want to replace Html.fromHtml("&#160") + "| Guys hi " + Pattern.compile("\\\\d+") with a "hey". But, my code doesn't want to do that :/ What should I change?

My code:

myString.replace(Html.fromHtml("&#160") + "| Guys hi " + Pattern.compile("\\d+"), "hey");

Explanation:

  • "&#160" represents a space in HTML
  • Pattern.compile("\\\\d+") finds any number at the end of string.

String replaceAll takes a regular expression, String replace does not. Using a pattern is an alternative option (not a supplementary one). Also, String (s) are immutable. You want something like,

myString = myString.replaceAll(Html.fromHtml("&#160") + "- Guys hi \\d+", "hey");

or

Pattern p = Pattern.compile(Html.fromHtml("&#160") + "- Guys hi \\d+");
Matcher m = p.matcher(myString);
myString = m.replaceAll("hey");

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