首页 > 解决方案 > 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;
}

标签: c++regexc++11

解决方案


一种选择是使用捕获组而不是使用lookbehind。在替换使用第一个捕获组$1使用regex_replace

^(ID;Type=[^:]+:).*

解释

  • ^字符串的开始
  • (捕获组 1
    • ID;Type=从字面上匹配
    • [^:]+::匹配除1 次以上的任何字符,然后匹配:
  • )关闭组
  • .*匹配任何字符 0+ 次

正则表达式演示| C++ 演示

例如

#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

推荐阅读