【问题标题】:Perl regex to match <foo>eofPerl 正则表达式匹配 <foo>eof
【发布时间】:2012-12-20 02:01:29
【问题描述】:

如何使用 Perl 正则表达式搜索来查找以以下结尾的文件:

-------\r\n<eof>

十六进制是:

2D 2D 2D 2D 0D 0A (the end of the file)

我在 UltraEdit 中,它说它使用 Boost Perl 正则表达式语法。

我已经想通了可以使用:

----\x0d\x0a

它确实找到了我想要的行,但仅在数百个不在文件末尾的行中:

whatever
------------     <- matches this also, which I don't want!
whatever
------------     <- matches this also, which I don't want!
whatever

【问题讨论】:

    标签: regex perl ultraedit


    【解决方案1】:

    UltraEdit 的正则表达式引擎以基于行的方式工作。这意味着它不区分行尾和文件尾。

    它也不知道\z\Z 字符串结束标记。此外,像 -----\r\n(?!.) 这样的否定前瞻断言在 UE 中也不起作用。

    所以 UE 的正则表达式引擎让您失望。你可以做的是使用宏:

    InsertMode
    ColumnModeOff
    HexOff
    Key Ctrl+END
    Key UP ARROW
    PerlReOn
    Find RegExp "-----\r\n"
    IfFound
    # Now do whatever you wanted to do...
    EndIf
    

    并让 UE 将其应用于您的所有文件。

    【讨论】:

      【解决方案2】:

      您是否需要遍历文件中的每一行并使用正则表达式?如果没有,只需 seek 到您需要的文件中的位置并检查字符串是否相等:

      open my $fh, '<', $the_file;
      seek $fh, 2, -6;            # seek to the end of file minus 6 bytes
      read $fh, my $x, 6;         # read 6 bytes into $x
      if ($x eq "----\r\n") {
          print "The end of file matches ----\\x0d\\x0a\n";
      } else {
          print "The end of file doesn't match ----\\x0d\\x0a\n";
      }
      

      【讨论】:

        【解决方案3】:

        这是使用 UltraEdit JavaScript 解决此问题的一种方法。

        使用 UltraEdit.activeDocument.bottom() 转到文件底部; 使用 UltraEdit.activeDocument.currentPos();存储您当前的位置。

        向后搜索“\r\n” 同样,使用 UltraEdit.activeDocument.currentPos();并将结果与​​之前的位置进行比较,以确定这是否实际上是文件末尾的 cr/lf。

        根据这些字符位置执行您想到的任何替换/插入,或抛出一个消息框来宣布结果。

        【讨论】:

          猜你喜欢
          • 2010-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多