Issue
I'm reviewing a my old php software and I need to do some general corrections. I'm trying to do some of them automatically by regex, but in some cases without success. I use Netbeans.
I need to substitute all:
$line[word_test]
with
$line['word_test']
excluding the case where word_test is a var (i.e. $abc) or a number or contains the string "const"
I tried with several regex like
\$line\[[^'|\$|constan](.*)\]
but without success. I need both the regex to write in the "Containing Text" field and that one to write in "Replace with" field of Netbeans replace functionality.
Solution
One option is to use capturing group with a negative lookahead.
(\$line\[)(?!\d|\$\w|[^\]]*const)([^\]]+)(\])
Explanation
(\$line\[)
Capture group 1, match$line[
(?!
Negative lookahead, assert what is directly to the right is not\d|\$\w|[^\]]*const
Match either a digit,$
followed by a word char orconst
)
Close lookahead([^\]]+)
Capture group 2, match any char except]
(\])
Capture group 3, match]
In the replacement use the 3 capturing groups
$1'$2'$3
In case there is an already existing format of $line['word_test1']
as @Nigel Ren points out in the comment, you could extend the negative lookahead:
(\$line\[)(?!'.*?'\]|\d|\$\w|[^\]]*const)([^\]]+)(])
Answered By - The fourth bird