简体   繁体   中英

Notepad++ replace text with RegEx search result

I would like replace a standard string in a file, with another that is a result of a regular expression. The standard text looks like:

<xsl:variable name="ServiceCode" select="###"/>

I would like to replace ### with a servicecode, that I can find later in the same file, from this URL:

<a href="/Services/xyz" target="_self">

The regular expression (?<=\\/Services\\/)(.*)(?=\\" ) returns the required service code "xyz".

So, I opened Notepad++, added "###" to the "Find what" and this RegEx to the "Replace with" section, and expected that the ### text will be replaced by xyz . But I got this result:

<xsl:variable name="ServiceCode" select="?<=/Services/.*?=" "/>

I am new to RegEx, do I need to use different syntax in the replace section than I use to find a string? Can someone give me a hint how to achieve the required result? The goal is to standardize tons of files with similar structure as now all servicecodes are hardcoded in several places in the file. Thanks.

You could use a lookahead for capturing the part ahead.

Search for: (?s)###(?=.*/Services/([^"]+)") and replace with: $1

  • (?s) makes the dot also match newlines (there is also a checkbox available in np++)
  • [^"] matches a character that is not "

The replacement $1 corresponds to capture of first parenthesized subpattern.

I am no expert at RegEx but I think I may be able to help. It looks like you might be going at this the wrong way. The regex search that you are using would normally work like this:

The parenthesis () in RegEx allow you to select part of your search and use that in the replace section.

You place (?<=\\/Services\\/)(.*)(?=\\" ) into the "Find what" section in Notepad++.

Then in the "Replace with" section you could use \\1 or \\2 or \\3 to replace the contents of your search with what was found in the (?<=\\/Services\\/) or (.*) or (?=\\" ) searches respectively.

Depending on the structure of your files, you would need to use a RegEx search that selects both lines of code (and the specific parts you need), then use a combination of \\1\\2\\3 etc. to replace everything exactly how it was, except for the ### which you could replace with the \\number associated with xyz .

See http://docs.notepad-plus-plus.org/index.php/Regular_Expressions for more info.

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