c++ - 在另一个正则表达式模式中使用已经定义的正则表达式模式以及关于将正则表达式应用于文件的问题
问题描述
如何在另一个正则表达式模式中使用已经定义的正则表达式模式。例如,在下面的代码中sign
和number
被定义,我想在定义中使用它们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
看起来像这样:
但我认为正则表达式不能正常工作:
它说没有单词匹配。问题出在哪里?
解决方案
在较大的正则表达式中“重用”较小的正则表达式的问题实际上是不可能的。
我能看到的唯一解决方法是将正则表达式的字符串定义为宏,并使用编译器的文字字符串连接功能来创建更大的字符串:
#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
对象,只会从较小的创建更长的文字字符串。
推荐阅读
- powerbi-desktop - POWER BI - 每个图像的不同工具提示
- java - 如何在 aether collectDependencies 中排除依赖项
- ios - 以 RTL 语言翻转的 SwiftUI 菜单内容
- migration - Bigcommerce 订单是否有其他详细信息和订单项属性
- android - android - 如何更改底部导航文本
- javascript - 从 discord.js 中的传入消息中获取命令
- javascript - Google 表格 - 脚本编辑器 数据验证生成器 - 格式化过滤日期列表
- php - 如何选择在 table1 中有值但在 table2 中为 NULL 的字段表?
- python - 模拟 NamedTemporaryFile 写入和关闭文件
- php - Hypens 打破 Laravel 动态路由