I am currently trying to improve the readability of some of my python scripts by adding spaces around the equal signs. For example, currently an assignment looks like this:
(?<=[\w\]\)])(=)(?=\w)
You can use this . Replacement by
" \1 "
See Demo.
http://regex101.com/r/vY0rD6/2
Your earlier regex had no captured pattern.So just added that.
With your initial regex,
Regex:
(?<=[\w\]\)])=(?=\w)
REplacement string:
=<space>
I added <space>
instead of .
Lookarounds would do a zero width match. It won't match any characters.
DEMO
The accepted answer to that question only contains the search expression. The question asker left a comment pointing out that the replacement string should be left empty. What that does is delete whatever is matched.
What you're looking to do here is not to delete the =
operators outright (as that would break your scripts quite catastrophically!), but simply to space-pad them.
What your original regex does:
(?<=[\w\]\)])=(?=\w)
Is find any =
character that
\w
, ]
or )
, as in (?<=[\w\]\)])
, and\w
, as in (?=\w)
.The (?<=)
and (?=)
portions are lookbehind and lookahead assertions respectively, not capture groups. Since your original regex doesn't capture anything, replacing with \1 = \2
won't work as expected.
In your working regex:
([\w\]\)])=(\w)
The ?<=
and ?=
tokens are removed which makes the two parentheticals capture groups. This allows the \1 = \2
backreferences to work, inserting spaces between the first capture, the =
sign, and the second capture appropriately.
On a side note (since you've already found a working solution), you can still make the original regex work, but the replacement string should simply be =
surrounded by spaces. The stuff that is tested by the lookbehind and lookahead assertions is never actually picked up — the only character that is matched is the =
sign itself — so it will not disappear when you replace.
In your first Regular Expression(?<=[\w\]\)])=(?=\w)
there's no capturing groups so you can't use back references (replacing with \1 = \2
)
But you can use space=space as replacement with the above regex where space is a real white space character.