简体   繁体   English

如何删除正则表达式中的特定代码部分

[英]How to delete a specific section of code in regex

<div class="pvs-list__footer-wrapper">
          <div class="pv2">
            <a class="optional-action-target-wrapper artdeco-button artdeco-button--tertiary artdeco-button--2 artdeco-button--muted 
      inline-flex justify-center align-self-flex-start
      
      " target="_self" href="https://www.linkedin.com/in/abhijit-vinchurkar/details/experience?profileUrn=urn%3Ali%3Afsd_profile%3AACoAAAF3rCwBitUseeMU1pitSb2GHhRHT87b2pI">
<!---->      <span class="pvs-navigation__text">
        Show all 6 experiences
      </span>
          </div>
      <div class="pvs-navigation__icon">

I want to delete lines from 'div class="pv2"' till the end of div section using regex.我想使用正则表达式从 'div class="pv2"' 删除行直到 div 部分结束。

To do only what you want, without handling the closing </div> tag, you could simply use this regex:只做你想做的事,而不处理结束</div>标记,你可以简单地使用这个正则表达式:

[ \t]*<div +class="pv2">[ \t]*\r?\n

It will search for spaces and tabs, zero or multiple times, then the div tag itself with one or more spaces before the class attribute.它将搜索空格和制表符,零次或多次,然后是 div 标记本身,在class属性之前有一个或多个空格。 But then it does not handle if it has other attributes.但是如果它有其他属性,它就不会处理。 It then also removes trailing spaces and the new line (Windows CRLF or Linux LF).然后它还会删除尾随空格和新行(Windows CRLF 或 Linux LF)。

Test it here: https://regex101.com/r/Kh6zmJ/1在这里测试它: https://regex101.com/r/Kh6zmJ/1

EDIT: question changed, you want to remove all the div tag with it's content编辑:问题已更改,您想删除所有 div 标签及其内容

Regexp isn't the best way to solve it because if some children inside this div are also divs then we could match the wrong closing div.正则表达式不是解决它的最佳方法,因为如果此 div 中的某些子项也是 div,那么我们可能会匹配错误的关闭 div。 Better use a DOM parser.最好使用 DOM 解析器。 But well, you want a quick way to edit multiple files.但是,您需要一种快速编辑多个文件的方法。 So if you know the HTML code then ok, let's use a regexp.因此,如果您知道 HTML 代码,那么好吧,让我们使用正则表达式。

It would be something like this:它会是这样的:

[ \t]*<div +class="pv2">[\s\S]*?</?div>[ \t]*\r?\n

The idea is normally to use .*?这个想法通常是使用.*? to match anything in an ungreedy way until the first closing </div> tag.以不贪婪的方式匹配任何东西,直到第一个结束</div>标记。 As VSCode doesn't handle the .由于VSCode不处理. to match also new lines with the s flag, you can replace .要将新行与s标志匹配,您可以替换. by [\s\S] which means any space or non-space character (so anything). [\s\S]表示任何空格或非空格字符(等等)。

Your closing div tag seems to be wrong so I put an optional slash with the questionmark after it.你的结束 div 标签似乎是错误的,所以我在它后面加上了一个带有问号的可选斜杠。

Test it here: https://regex101.com/r/LdvzHU/1在这里测试: https://regex101.com/r/LdvzHU/1

In VSC在 VSC 中

  • place cursor somewhere in tag <div class="pv2">将 cursor 放在标签<div class="pv2">的某处
  • execute command Emmet: Balance (outward)执行命令Emmet: Balance (outward)
  • Delete删除

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

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