简体   繁体   中英

Replace with Regex in Notepad++

I'm trying to replace the part the text with the same text and some extra, example:

Initial text

<href="../doc/d5807346.pdf" class="document">3.2.1.&nbsp;&nbsp;&nbsp;&nbsp;EXAMPLE</a></div><div style="clear:both;"></div>

After

<href="../doc/d5807346.pdf" class="document" download="3.2.1.&nbsp;&nbsp;&nbsp;&nbsp;EXAMPLE">3.2.1.&nbsp;&nbsp;&nbsp;&nbsp;EXAMPLE</a></div><div style="clear:both;"></div>

I'm using in Notepad++ the following Regex:

  • Find: ((?<=class="document">).*?(?=<))
  • Replace with: download="\1">\1

End result is not what I'm expecting, note the > between class="document" and download:

<href="../doc/d5807346.pdf" class="document"> download="3.2.1.&nbsp;&nbsp;&nbsp;&nbsp;EXAMPLE">3.2.1.&nbsp;&nbsp;&nbsp;&nbsp;EXAMPLE</a></div><div style="clear:both;"></div>

I'm stuck on trying to figure out how to prevent that.

Try this:

  1. Find: (?:class="document">)([^<]*)
  2. Replace (corrected): class="document">download="$1">$1

Tested in N++

Before: <href="../doc/d5807346.pdf" class="document">3.2.1.&nbsp;&nbsp;&nbsp;&nbsp;EXAMPLE</a></div><div style="clear:both;"></div>

After: <href="../doc/d5807346.pdf" class="document">download="3.2.1.&nbsp;&nbsp;&nbsp;&nbsp;EXAMPLE">3.2.1.&nbsp;&nbsp;&nbsp;&nbsp;EXAMPLE</a></div><div style="clear:both;"></div>

It's helpful to Use "online Regex tester" for visual debug regular expression

  • Ctrl + H
  • Find what: (class="document")>([^<]+)
  • Replace with: $1 download="$2">$2
  • CHECK Wrap around
  • CHECK Regular expression
  • Replace all

Explanation:

(class="document")      # group 1
>                       # literally >
([^<]+)                 # group 2, 1 or more any character that is not "<"

Replacement:

$1              # content of group 1 + a space
download="      # literally
$2              # content of group 2
">              # literally
$2              # content f group 2

Screenshot (before):

在此处输入图像描述

Screenshot (after):

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM