首页 > 解决方案 > 在另一个正则表达式模式中使用已经定义的正则表达式模式以及关于将正则表达式应用于文件的问题

问题描述

如何在另一个正则表达式模式中使用已经定义的正则表达式模式。例如,在下面的代码中signnumber被定义,我想在定义中使用它们relation

regex sign("=<|=|>|<=|<>|>=");
regex number("^[1-9]\\d*");
regex relation(number, sign, number)

因此,我需要在给定的文件23<=34中找到所有匹配项(与or类似的模式) 。123<>2000

由于我还没有完成relation,我一直在测试sign

#include <iostream>
#include <fstream>
#include <regex>
using namespace std;

int main() {
  regex sign("=<|=|>|<=|<>|>=");
  regex digit("[0-9]");
  regex number("^[1-9]\\d*"); 
  //regex relation("^[1-9]\d*[=<|=|>|<=|<>|>=]^[1-9]\d*"); (this part is what I couldn't do)

  string line;

  ifstream fin;
  fin.open("name.txt");

  if (fin.good()) {
    while (getline(fin, line)) {
      bool match_sign = regex_search(line, sign);
      if (match_sign) {
        cout << line << endl; // but I need to print the match only
      }
    }
  }
  return 0;

}

当我想打印文件中的匹配项时,它会打印包含任何匹配项的整行。我怎样才能让它只打印匹配本身而不是整行?


更新:

#include <iostream>
#include <fstream>
#include <vector>
#include <regex>
using namespace std;
#define REGEX_SIGN   "=<|=|>|<=|<>|>="
#define REGEX_DIGIT  "[0-9]"
#define REGEX_NUMBER "^" REGEX_DIGIT "\\d*"

int main() {
  regex sign(REGEX_SIGN);
  regex digit(REGEX_DIGIT);
  regex number(REGEX_NUMBER); 
  regex relation(REGEX_NUMBER REGEX_SIGN REGEX_NUMBER);
  string line, text;

  ifstream fin;
  fin.open("name.txt");

  if (fin.good()) {

    while (getline(fin, line)) {
      text += line + " ";
    }

    int count = 0;
    string word = "";

    for (int i = 0; i < text.length(); i++) {

      if (text[i] == ' ') {
        cout << "word = " << word << " | match: " << regex_match(word, relation) << endl;
        if (regex_match(word, relation)) {
          cout << word << endl;
        }

        word = "";
      } 
      else {
        word += text[i];
      }
    }
  }
  // cout << text << endl;
  return 0;
}

当前name.txt看起来像这样:


在此处输入图像描述


但我认为正则表达式不能正常工作:


在此处输入图像描述


它说没有单词匹配。问题出在哪里?

标签: c++regexfile

解决方案


在较大的正则表达式中“重用”较小的正则表达式的问题实际上是不可能的。

我能看到的唯一解决方法是将正则表达式的字符串定义为宏,并使用编译器的文字字符串连接功能来创建更大的字符串:

#define REGEX_SIGN   "=<|=|>|<=|<>|>="
#define REGEX_DIGIT  "[0-9]"
#define REGEX_NUMBER "^" REGEX_DIGIT "\\d*"

regex sign(REGEX_SIGN);
regex digit(REGEX_DIGIT);
regex number(REGEX_NUMBER); 
regex relation(REGEX_NUMBER REGEX_SIGN REGEX_NUMBER);

这不会重用实际的regex对象,只会从较小的创建更长的文字字符串。


推荐阅读