在记事本++中使用正则表达式替换 [英] Replace using RegEx in notepad++

查看:49
本文介绍了在记事本++中使用正则表达式替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 xyz 替换标记为 的 XML 文件中的所有名称.换句话说,替换标签之间的所有内容(包括空格).我做错了什么?

I would like to replace all names in an XML file tagged by with let's say xyz. In other words, replace everything (including whitespace) between the tags. What am I doing wrong?

Search: (<name>)(.*)(</name>)
Replace: \1xyz\3

推荐答案

您正在尝试 使用正则表达式解析 XML.

但是,无论如何,您做错的是使用贪婪的重复.这将从第一个 一直到最后一个 (即使它们不属于一起),因为 .* 将在满足匹配条件的同时尝试尽可能多地消耗.. 改用这个:

However, what you are doing wrong anyway is using a greedy repetition. This will go all the way from the first <name> to the very last </name> (even if they do not belong together), because the .* will try to consume as much as possible while still fulfilling the match condition.. Use this instead:

Search: (<name>).*?(</name>)
Replace: \1xyz\2

或者为了安全起见,您也可以转义 <>,因为它们在某些特定情况下是元字符(不是在这种情况下)虽然):

Or to be on the safe side you can also escape the < and >, since they are meta-characters in some specific cases (not in this one though):

Search: (\<name\>).*?(\</name\>)
Replace: \1xyz\2

在这两种情况下,这都会使 .* 不贪婪,即它会尽可能少地消耗.

In both cases, this makes the .* ungreedy, i.e. it will consume as little as possible.

并确保您升级到 Notepad++ 6,因为在此之前 Notepad++ 的正则表达式引擎存在一些问题.

And make sure you upgrade to Notepad++ 6, because before that there were a few issues with Notepad++'s regex engine.

最后,正如 hoombar 在评论中指出的那样 . 默认匹配每个字符 except 换行符.在 Notepadd++ 中,您可以通过勾选 来更改此行为.匹配换行符复选框.

Lastly, as hoombar pointed out in a comment . by default matches every character except line break characters. In Notepadd++ you can change this behavior by ticking the . matches newline checkbox.

这篇关于在记事本++中使用正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆