I need java pattern for string not bounded by a character.
I have a string (as mentioned below), with some curly brackets bounded by single quotes and other curly brackets that are not. I want to replace the curly brackets that are not bounded by single quotes, with another string.
Original string:
this is single-quoted curly '{'something'}' and this is {not} end
Needs to be converted to
this is single-quoted curly '{'something'}' and this is <<not>> end
Notice that the curly brackets { } that are not bounded by single quotes have been replaced with << >>.
However, my code prints (character gets eaten up) the text as
this is single-quoted curly '{'something'}' and this is<<no>> end
when I use the pattern
[^']([{}])
My code is
String regex = "[^']([{}])";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
if ( "{".equals(matcher.group(1)) ) {
matcher.appendReplacement(strBuffer, "<<");
} else if ( "}".equals(matcher.group(1))) {
matcher.appendReplacement(strBuffer, ">>");
}
}
matcher.appendTail(strBuffer);
This is a clear use case for zero-width assertions. The regex you need isn’t very complex:
prints