1

I have this string with HTML inside: <span title="whatever">something I want to preserve</span>...

I'm using a regex to replace <span title="whatever"> with ( and then the following </span> replace with )

Pattern regex = Pattern.compile("<span\\s+[^>]*title=(['\"])(.*?)\\1[^>]*>");
Matcher matcher = regex.matcher(strLine);
if (matcher.find()) {
    strLine = matcher.replaceAll("(");
    strLine = strLine.replace("</span>", ")");
}

I works but it replaces all </span> tags; I only want to replace the one that matches the opening tag I just matched.

2
  • Have you tried replace instead of replaceAll ? Commented Nov 11, 2011 at 12:20
  • So if I understand you correctly, you need to replace any span with a title with (), but any span that does not have a title you want to leave alone. And the problem that you have above is that the opening tags <span> are being replaced correctly, but too many of the closing tags </span> are being replaced (ie. the ones matching opening tags without title. Is this correct? Commented Nov 11, 2011 at 12:25

3 Answers 3

6

Why not do it in one replaceAll(...) call:

String s = "noise <span title=\"whatever\">something I want to preserve</span>...";
s = s.replaceAll("<span\\s+[^>]*title=(['\"])(.*?)\\1[^>]*>(.*?)</span>", "($3)");
System.out.println(s);

which will print:

noise (something I want to preserve)...

EDIT

Note Alan's comment under my answer: this assumes you don't have nested <span>'s in your input.

Sign up to request clarification or add additional context in comments.

1 Comment

This assumes there won't be any other <span> elements nested inside the one you're matching.
3

I suggest you use a single regex for matching the entire <span ...>...</span>. Capture the <span> in one group and the </span> in another and use the capture groups to do the replacement.

Comments

1

Instead of replacing the <span> tags, you could try to extract the content of the <span> tag and then wrap it with braces.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.