Difficulties with adding spaces around equal signs using regular expressions with Notepad++

前端 未结 4 1603
花落未央
花落未央 2021-01-14 18:22

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:

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-14 19:20

    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

    • is preceded by one of \w, ] or ), as in (?<=[\w\]\)]), and
    • is followed by a \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.

提交回复
热议问题