I am using Java to parse through a JavaScript file. Because the scope is different than expected in the environment in which I am using it, I am trying to replace every instance of i.e.
test = value
with
window.test = value
Previously, I had just been using
writer.append(js.getSource().replaceAll("test", "window.test"));
which obviously isn't generalizable, but for a fixed dataset it was working fine.
However, in the new files I'm supposed to work with, an updated version of the old ones, I now have to deal with
window['test'] = value
and
([[test]])
I don't want to match test
in either of those cases, and it seems like those are the only two cases where there's a new format. So my plan was to now do a regex to match anything except '
and [
as the first character. That would be ([^'\[])test
; however, I don't actually want to replace the first character - just make sure it's not one of the two I don't want to match.
This was a new situation for me because I haven't worked with replacement with RegExps that much, just pattern matching. So I looked around and found what I thought was the solution, something called "non-capturing groups". The explanation on the Oracle page sounded like what I was looking for, but when I re-wrote my Regular Expression to be (?:[^'\\[])test
, it just behaved exactly the same as if I hadn't changed anything - replacing the character preceding test
. I looked around StackOverflow, but what I discovered just made me more confident that what I was doing should work.
What am I doing wrong that it's not working as expected? Am I misusing the pattern?