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.
Why not do it in one
replaceAll(...)call:which will print:
EDIT
Note Alan’s comment under my answer: this assumes you don’t have nested
<span>‘s in your input.