replace after “word” character by character in not

2019-07-10 10:59发布

问题:

I have a STRING

"wordride plain fire "

I have tried to replace with Regular Expressions:

  • Find what: (?>(word)|\G(?<!^))\K\S
  • Replace with: $1$2$0

In Notepad ++, it does not change the text but it works in regex101 (https://regex101.com/r/aI6gE1/2), where i replaces characters after word as follows

  • First replace: wordwordide plain fire
  • Second replace: wordwordwordde plain fire
  • Third replace: wordwordwordworde plain fire
  • Fourth replace: wordwordwordwordword plain fire
  • Fifth replace: wordwordwordwordwordwordplain fire
  • Sixth replace: wordwordwordwordwordwordwordlain fire

Can you help me to see the error or give me a workaround in Notepad ++ for this purpose: replacing string after "word" character by character using a group not included in match group

Please help me

回答1:

The answer is yes, it is possible to do with Notepad++ BUT only with the help of a PythonScript plug-in.

Get the plugin ready, and create the following script:

import re

regex = r"^(word)(.+)"

def process_match(match):
    return "{0}{1}".format(match.group(1), "".join([match.group(1) for x in list(match.group(2))]))
editor.rereplace(regex, process_match)

The ^(word)(.+) pattern will match a line with word at its start into Group 1 and all the rest of the line into Group 2.

The "{0}{1}".format(match.group(1), "".join([match.group(1) for x in list(match.group(2))])) will paste the Group 1 value into the result first (see format(match.group(1)) and then "".join([match.group(1) for x in list(match.group(2))]) will replace each character in Group 2 with the value in Group 1.

This text:

word1
word1 2
wordride plain fire 

will turn into:

NOTE: You can control how many chars after word are replace with word by adjusting (modifying) the (.+) pattern.



回答2:

It's hard to understand exactly what you want to do but the following is working based on your examples:

  • Find: ^((word)+).
  • Replace with: $1$2