0

I want to replace &sp; in the string below with Z.

Input text : ABCD&sp;EF&p;GHIJ&bsp;KL

Output text : ABCDZEFZGHIZKL

Can anyone tell me how to replace the every instance of &\D+; using java regular expression?

I am using /(&\D+;)?/ but it doesn't work.

Johannes
  • 6,490
  • 10
  • 59
  • 108
mia
  • 1,148
  • 1
  • 11
  • 17

2 Answers2

2

Use String#replaceAll.

You also should use the ? modificator to +:

String str = "ABCD&sp;EF&p;GHIJ&bsp;KL";
String regex = "&\\D+?;";
System.out.println (str.replaceAll(regex,"Z"));

This should work

dquijada
  • 1,697
  • 3
  • 14
  • 19
0

Match the initial &, then all characters that are not the tailing ;, then that tailing ; like so: &[^;]+; If not matching numbers (as suggested by your example with \D) is a requirement, add the numbers to the negated character set: [^;0-9] To make it replace all occurrences, add the global flag g. The site regexr.com is a handy tool to create regexes.

Edit: Sorry, I initially read your question wrong.

Christallkeks
  • 525
  • 5
  • 18