简体   繁体   English

如何在变量中存储正则表达式匹配以与Notepad ++中的“搜索/替换”一起使用

[英]How to store regex match in a variable to use with Search/Replace in Notepad++

I need to capture a word using a pattern and store somewhere to use in replace operation: 我需要使用模式捕获一个单词并存储在某个地方以用于替换操作:

For instance I have this text 例如,我有这个文本

ab iiids
as sasas
md aisjaij
as asijasija

I am able to capture everething before the first space using the following pattern: 我可以使用以下模式捕获第一个空格之前的所有内容:

.*?(?=[" "])

Let´s say I could use '$' to represent the match in the search and replace so I would like to have the following in the replace field 假设我可以使用'$'代表搜索和替换中的匹配,所以我想在替换字段中包含以下内容

INSERT INTO table (value) VALUES ("$")

Could not find a solution. 找不到解决方案。 Is this even possible? 这甚至可能吗?

Yes, $& or $0 represents the entire match in the replacement string: 是的, $&$0表示替换字符串中的整个匹配:

Find what: .*?(?=[ ])
Replace with: INSERT INTO table \(value\) VALUES \("$0"\)

Note that you don't need the quotes inside the character class. 请注意,您不需要字符类中的引号。 Otherwise your match will stop at a quote as well. 否则你的比赛也将在报价处停止。 Also note, that there is another catch, that you have to escape parentheses in the replacement string (thanks to acdcjunior for noticing that). 还要注意,还有另一个问题,你必须在替换字符串中转义括号(感谢acdcjunior注意到)。 That's because Notepad++ uses boost, which supports a parenthesis-delimited conditional construct. 这是因为Notepad ++使用boost,它支持括号分隔的条件结构。

Using your input, this will result in 使用您的输入,这将导致

INSERT INTO table (value) VALUES ("ab") iiids
INSERT INTO table (value) VALUES ("as") sasas
INSERT INTO table (value) VALUES ("md") aisjaij
INSERT INTO table (value) VALUES ("as") asijasija

For more advanced use cases, you can wrap parts of the regex in parentheses, and reference the substrings they matched with $1 , $2 , and so on. 对于更高级的用例,您可以将正则表达式的部分包装在括号中,并引用它们与$1$2匹配的子字符串。

By the way, a more explicit pattern would be: 顺便说一下,更明确的模式是:

^[^ ]*(?=[ ])

This makes sure that you don't get additional matches where you don't want them. 这可以确保您不会在不需要的地方获得其他匹配项。

Finally, here is a reference of all the things you can do in the replacement string. 最后, 这里是您可以在替换字符串中执行的所有操作的参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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