0

String url : <a href='https://sample.com'>Example:</a>

I want to keep text Example: How to use replaceAll to do remove/replace with " "?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
fizz
  • 69
  • 1
  • 9
  • 2
    `replaceAll` uses regex syntax which is not right tool for that job (for reasons why see: [Using regular expressions to parse HTML: why not?](https://stackoverflow.com/q/590747), [Can you provide some examples of why it is hard to parse XML and HTML with a regex?](https://stackoverflow.com/q/701166)). To handle HTML use HTML parser like `jsoup` which lets us write code like [How to get text from this html tag by using jsoup?](https://stackoverflow.com/q/15946200) – Pshemo Aug 14 '19 at 08:53
  • sorry~ I have this string input from user~ so i need to handle it for removing head and tail or just take the text out~ – fizz Aug 14 '19 at 08:59
  • Solution from linked question seems to apply here. Check if `String replaced = Jsoup.parse(textFromUser).body().text();` does what you wanted (be sure to include to your application jsoup library). – Pshemo Aug 14 '19 at 09:06

1 Answers1

3

Particularly for your case:

String url = "<a href='https://sample.com'>Example:</a>";
String text = url.replaceAll("<a.*>\\b", "").replaceAll("</a>", ""));
shade
  • 71
  • 4
  • If space can be after `Example: ` there is also a risk that user will also add it (one or more) before it like ` Example:` in which case `.replaceAll("\\b", "")` will fail. There are many traps which will need to be solved while writing regex solution. Better approach would be using tools *designed* to handle this kind of situations which is HTML parser. – Pshemo Aug 14 '19 at 09:57
  • the best comment ever! and also I find another way~~~ replaceAll("(.+)<\\/a>", "$1") – fizz Aug 14 '19 at 10:08
  • Pshemo, that's why I've declared the solution is particularly for this case. – shade Aug 14 '19 at 11:17