Search code examples
javaregexstringreplaceall

Replace a string without certain prefix and suffix in Java


I'm trying to replace all ocurrences of a given string, but I have to be sure that it isn't surrounded with letters or numbers.

For example:

// Directive's block
BIT EQU $1111
BIT0 EQU $0000

// Instruction's block
ADD BIT, (**BIT**0)+

When my parser founds an EQU in the first line, it reads the instruction's block trying to find the given label ("BIT", in this case) and replacing it with its value. Then the result is (which is wrong):

ADD $1111, (**$1111**0)+

Overriding the name of the other label, cause it is a substring of it. So I have to be sure that the surrounded characters are not letters or numbers, then I can be sure that it doesn't overrides another label ID.

My code for now is:

output += operand.replace(label, value)+" ";

operand: a string containing the whole operand label: the label to be found for replacement value: the value to be replaced with that label

Now i'm trying to use ReplaceAll() and some regex:

String regex = "(?<![a-zA-Z_])"+label+"[^a-zA-Z_]";

output+= operand.replaceAll(regex, value)+" ";

But it throws the following exception:

IndexOutOfBoundsException: Non group 1 (java.util.regex.Matcher.start)

Even if I left only the suffix, it throws the same error.

Does anybody knows what does it means?

Thanks you guys.


Solution

  • If you're using replaceAll() and you're trying to replace something with $1111, that won't work, because $ has a special meaning in replaceAll. Use Matcher.quoteReplacement(value) instead of value in the replaceAll() call; quoteReplacement makes sure that any special characters are "quoted" so that they no longer have special meanings. (The replacement is interpreting $1 as "replace with the contents of group 1", which is why you're getting the error.)