簡體   English   中英

提取兩個其他模式之間的匹配線

[英]Extract matching lines between two other patterns

我試圖在C ++中使用正則表達式來提取與某個單詞相匹配的行 - 來自由兩個其他模式限定的文件中的區域內。 我還想打印每場比賽的行號。

我目前正在使用popen運行perl命令,但我想用C ++來做:

perl -ne 'if ((/START/ .. /END/) && /test/) {print "line$.:$_"}' file

此命令在STARTEND之間查找區域,然后從包含單詞test那些提取線中查找。

如何使用C ++中的正則表達式執行此操作?

Perl的語義..是微妙的。 下面的代碼模擬了..-n切換到perl隱含的while (<>) { ... }

#include <fstream>
#include <iostream>
#include <regex>
#include <vector>

// emulate Perl's .. operator
void flipflop(bool& inside, const std::regex& start, const std::regex& end, const std::string& str)
{
  if (!inside && std::regex_match(str, start))
    inside = true;
  else if (inside && std::regex_match(str, end))
    inside = false;
}

int main(int argc, char *argv[])
{
  // extra .* wrappers to use regex_match in order to work around
  // problems with regex_search in GNU libstdc++
  std::regex start(".*START.*"), end(".*END.*"), match(".*test.*");

  for (const auto& path : std::vector<std::string>(argv + 1, argv + argc)) {
    std::ifstream in(path);
    std::string str;
    bool inside = false;
    int line = 0;
    while (std::getline(in, str)) {
      ++line;
      flipflop(inside, start, end, str);
      if (inside && std::regex_match(str, match))
        std::cout << path << ':' << line << ": " << str << '\n';

      // Perl's .. becomes false AFTER the rhs goes false,
      // so keep this last to allow match to succeed on the
      // same line as end
      flipflop(inside, start, end, str);
    }
  }

  return 0;
}

例如,請考慮以下輸入。

test ERROR 1
START
test
END
test ERROR 2
START
foo ERROR 3
bar ERROR 4
test 1
baz ERROR 5
END
test ERROR 6
START sldkfjsdflkjsdflk
test 2
END
lksdjfdslkfj
START
dslfkjs
sdflksj
test 3
END dslkfjdsf

樣品運行:

$ ./extract.exe file
file:3: test
file:9: test 1
file:14: test 2
file:20: test 3

$ ./extract.exe file file
file:3: test
file:9: test 1
file:14: test 2
file:20: test 3
file:3: test
file:9: test 1
file:14: test 2
file:20: test 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM