1

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.
6
  • I'm pretty sure you're using regex correctly... (maybe?) Commented Jul 29, 2017 at 19:00
  • 3
    Erm... What...? Commented Jul 29, 2017 at 19:01
  • @MateusA. then, how can you explain my code not working? Commented Jul 29, 2017 at 19:01
  • What is this Pattern.compile("\\d+") supposed to do? Regex (or Patterns) is for text matching/validating... It won't be turned into a number/text. Commented Jul 29, 2017 at 19:02
  • 3
    Pattern.compile("\\d+") only creates pattern which describes one or more digits, but it doesn't automatically find it. It is your job to decide how to use it. From what I see you could be looking for replaceAll(regex, replacement). Commented Jul 29, 2017 at 19:06

1 Answer 1

4

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");
Sign up to request clarification or add additional context in comments.

3 Comments

I'm testing this, I'm encountering a few issues. I'll be back to you soon!
It works, but I made a typing mistake in the question. It's now edited. The - is supposed to be a |. Using your first line of code, the | doesn't get replaced. How can we fix this?
Escape a literal | with \ like \\|.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.