【问题标题】:Looking for a string with regex and delete the whole line用正则表达式查找字符串并删除整行
【发布时间】:2016-10-30 02:33:40
【问题描述】:

我试图在 Textpad 中查找带有正则表达式的字符(例如“#”),如果找到,则应删除整行。 # 既不在行首也不在行尾,而是介于两者之间,并且不连接到另一个单词、数字或字符 - 它与左右一个空格独立存在,但当然该行的其余部分包含单词和数字。

例子:

My first line
My second line with # hash
My third line# with hash

结果:

My first line
My third line# with hash

我怎样才能做到这一点?

【问题讨论】:

    标签: regex textpad


    【解决方案1】:

    让我们分解一下:

    ^     # Start of line
    .*    # any number of characters (except newline)
    [ \t] # whitespace (tab or space)
    \#    # hashmark
    [ \t] # whitespace (tab or space)
    .*    # any number of characters (except newline)
    

    或者,在一行中:^.*[ \t]#[ \t].*

    【讨论】:

    • 这很好,谢谢,但是有没有办法让线条向上移动?到目前为止,当我什么都不用替换它时,Textpad 保持空行。
    • 在这种情况下,您还需要匹配尾随的\r\n。只需将(\r\n)? 添加到正则表达式的末尾(由于文件的最后一行可能缺少换行符而成为可选的)。
    【解决方案2】:

    试试这个

    ^(.*[#].*)$
    

    Debuggex Demo

    或许

    (?<=[\r\n^])(.*[#].*)(?=[\r\n$])
    

    Debuggex Demo

    【讨论】:

      【解决方案3】:

      编辑:更改以反映蒂姆的观点

      这个

      public static void main(String[] args){
          Pattern p = Pattern.compile("^.*\\s+#\\s+.*$",Pattern.MULTILINE);
      
          String[] values = {
              "",
              "###",
              "a#",
              "#a",
              "ab",
              "a#b",
              "a # b\r\na b c"
          };
          for(String input: values){
              Matcher m = p.matcher(input);
              while(m.find()){
                  System.out.println(input.substring(m.start(),m.end()));
              }
      
          }
      }
      

      给出输出

      a # b
      

      【讨论】:

      • 这基本上是我的正则表达式正在做的事情,但有一个问题:\s 也匹配换行符,因此a #\nbc 的两行也将被匹配/删除。
      • @TimPietzcker:修复它。
      猜你喜欢
      • 2021-05-31
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      相关资源
      最近更新 更多