-2

I use a String where I need to get rid of any occurence of: < any string here >

I tried line = line.replaceAll("<[.]+>", "");

but it gives the same String... How can I delete the < any string between > substrings?

darkchampionz
  • 1,174
  • 5
  • 24
  • 47

2 Answers2

2
line = line.replaceAll("<[^>]*>", "");
Friederike
  • 1,252
  • 15
  • 29
2

As per my original comment...

Brief

Your regex <[.]+> says to match <, followed by the dot character . (literally) one or more times, followed by >

Removing [] will get you a semi-appropriate answer. The problem with this is that it's greedy, so it'll actually replace everything from the first occurrence of < to the last occurrence of > in the entire string (see the link to see it in action).

What you want is to either make the quantifier lazy or use a character class to ensure it's not going past the ending character.


Code

Method 1 - Lazy Quantifier

This method .*? matches any character any number of times, but as few as possible

See regex in use here

<.*?>

Method 2 - Character Set

This method [^>]* matches any character except > any number of times

See regex in use here

<[^>]*>

Note: This method performs much better than the first.

ctwheels
  • 21,901
  • 9
  • 42
  • 77