c++ - C++ 随机正则表达式替换文件
问题描述
我想从包含更多 ID 的文件中替换 ID 并使其随机化。我真的很难通过它。任何的想法?
ID_List.txt:
Begin
Name: Person
Phone;type=Main:+1 234 567 890
ID;Type=Main:132dfi987416
End
Begin
Name: OtherPerson
Phone;type=Main:5598755131
ID;Type=Main:549875413213
ID;Type=Seco:987987565oo2
End
Begin
Name: TheOtherPerson
Phone;type=Main:+58 321 654 987
ID;Type=Main:6565488oop24
ID;Type=Seco:7jfgi0897540
ID;Type=Depr:6544654650ab
End
我必须使用 C++,并认为正则表达式可能是我的出路。因此我的
正则表达式:
(?<=ID;Type=....:).*$
C++:
#include <iostream>
#include <math>
#include <string>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <regex>
#include <iterator>
using namespace std;
string in_file;
srand (time(NULL));
void write();
int randomizer();
int main() {
int a,b,c,x,y,z,n;
cout << "Input File: "; getline(cin, in_file);
return 0;
}
void write() {
fstream source;
source.open(in_file.c_str());
? CODE HERE ?
}
int randomizer (){
int x;
X = rand() % 10 + 0;
return x;
}
解决方案
一种选择是使用捕获组而不是使用lookbehind。在替换使用第一个捕获组$1
使用regex_replace
^(ID;Type=[^:]+:).*
解释
^
字符串的开始(
捕获组 1ID;Type=
从字面上匹配[^:]+:
:
匹配除1 次以上的任何字符,然后匹配:
)
关闭组.*
匹配任何字符 0+ 次
例如
#include <iostream>
#include <regex>
int main (int argc, char* argv[])
{
std::cout << std::regex_replace("ID;Type=Main:132dfi987416", std::regex("^(ID;Type=[^:]+:).+"), "$1REPLACEMENT");
}
输出
ID;Type=Main:REPLACEMENT
推荐阅读
- java - 如何通过 json 将本地图像(可绘制图像文件)显示到 cardview。我想离线加载图像而不是使用毕加索库
- c# - Shared method to return string only if needed
- python - gTTS 无法保存文件两次
- postgresql - PostgreSQL:从代码执行查询时“pq:关系列不存在”,但在控制台中工作正常
- mongodb - MongoDB sorting by date as type String
- java - 处理不稳定的反应式 API
- python - 在地图函数中除以 0
- python - 如何解决这个 Typeerror?
- android - 搜索 ListView 不起作用
- vba - Tranfser data between two closed workbooks without creating a new one