Reputation: 1745
Okay, so I'm trying to use my text editor (sublime text) to do a find and replace in regex mode. I have hundreds of strings in multiple files that contain [some_text] that need to be converted to ['some_text']. The following works for matching and replacing the starting brackets without quotes after:
find: \[(?!')
replace: ['
However, the same logic for finding the closing brackets without quotes before seems to be matching all closing brackets, even those with quotes before. Any ideas?
find: (?!')\]
replace: ']
Upvotes: 2
Views: 561
Reputation: 44259
You need to use a lookbehind instead of a lookahead in the second case:
find: (?<!')\]
replace: ']
The reason is that the lookahead (?!...)
looks to the right of the regex engine's current position. So if you want to match a ]
and execute a lookahead in front of it, the regex engine will check that against the ]
itself, which (of course) is not a '
.
The lookbehind on the other hand looks to the left of the regex engine's current position, which is exactly what you want.
Note that in both cases the lookarounds do not consume any characters! Checking them does not advance the position of the regex engine. This is why the direction of the lookaround is relevant.
You can read some more details about lookarounds and regex engine internals here.
(Just as a side note, you usually don't need to escape ]
. Without an opening [
it can never be mistaken for a meta-character.)
Upvotes: 2