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

前端 未结 4 1563
花落未央
花落未央 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:08
      (?<=[\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.

    0 讨论(0)
  • 2021-01-14 19:19

    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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-14 19:24

    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.

    0 讨论(0)
提交回复
热议问题