是否有正则表达式可以搜索一组行并替换该组中的一行? [英] Is there a regex that can search in a group of lines and replace one line within that group?

查看:121
本文介绍了是否有正则表达式可以搜索一组行并替换该组中的一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有类似的东西:



for example if I have something like:

<Directory />
  word
  box
  car
</Directory>





有没有方法,以确保使用正则表达式,只有在文件中的那个组我可以替换框,让我们说驱动器。使其成为:





Is there a way to make sure using regex that only in that group in the file I can replace box with lets say drive. To make it like:

<Directory />
  word
  drive
  car
</Directory>







这里的关键是确保它在该目录组中。

那么我如何用驱动器替换盒子?



我尝试了什么:



我尝试使用正则表达式:




The key here is to ensure its in that directory group.
So how would i replace box with drive?

What I have tried:

I have tried using a regex that states:

(<Directory />\s+)box(\s+</Directory>)





和我的替换是:



and my replace was:

\1drive\2



但这里的问题是如果上面或下面有单词的话它找不到它。


but the problem here is if there is words above or below box it wont find it.

推荐答案

引用:

是否有正则表达式可以在一组行中搜索并替换该组中的一行?

Is there a regex that can search in a group of lines and replace one line within that group?



简答:是的!

您的RegEx:'( <目录/> \s +)框(\s +< /目录>)'

匹配:'<目录/>框< /目录> '

您需要改进RegEx以包含换行符和单词以及空格,例如替换 \s + (\ s | \ n | \w)+



只是一些有趣的链接来帮助构建和调试RegEx。

以下是RegEx文档的链接:

perlre - perldoc.perl.org [ ^ ]

以下是帮助构建RegEx并调试它们的工具的链接:

.NET Regex Tester - Regex Storm [ ^ ]

Expresso正则表达式工具 [ ^ ]

RegExr:Lea rn,Build,&测试RegEx [ ^ ]

在线正则表达式测试器和调试器:PHP,PCRE,Python,Golang和JavaScript [ ^ ]

这个显示RegEx是一个很好的图表,它非常有助于理解RegEx的作用:

Debuggex:在线可视正则表达式测试器。 JavaScript,Python和PCRE。 [ ^ ]

这个网站也在一个漂亮的图表中显示正则表达式,但无法测试与RegEx匹配的内容:

Regexper [ ^ ]


Short answer: Yes !
Your RegEx: '(<Directory />\s+)box(\s+</Directory>)'
is matching: '<Directory /> box </Directory>'
You need to improve the RegEx to include the newlines and words along with spaces, like replacing \s+ with (\s|\n|\w)+.

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
Online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
This site also show the Regex in a nice graph but can't test what match the RegEx:
Regexper[^]


这篇关于是否有正则表达式可以搜索一组行并替换该组中的一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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