2

I want to replace ID from file containing many more ID and make it random. I really struggle to get it through. Any idea?

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

I have to use C++ and thought that regex could be my way out. Thus my

regex:

(?<=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;
}
Ðаn
  • 10,934
  • 11
  • 59
  • 95
KotjengOren
  • 79
  • 1
  • 7

1 Answers1

1

One option is to use a capturing group instead of using the lookbehind. In the replacement use the first capturing group $1 using regex_replace

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

Explanation

  • ^ Start of string
  • ( Capture group 1
    • ID;Type= Match literally
    • [^:]+: Match any char except : 1+ times, then match :
  • ) Close group
  • .* Match any char 0+ times

Regex demo | C++ demo

For example

#include <iostream>
#include <regex>

int main (int argc, char* argv[])
{
    std::cout << std::regex_replace("ID;Type=Main:132dfi987416", std::regex("^(ID;Type=[^:]+:).+"), "$1REPLACEMENT");
}

Output

ID;Type=Main:REPLACEMENT
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • Appreciate the regex option, but i need to change the string behind it not the first group or the whole thing. am i correct or i just don't get what you meant. – KotjengOren Apr 18 '20 at 07:14
  • @KotjengOren The pattern matches the whole string, captures in group 1 what you want to keep and matches what you want to remove. In the replacement, you use the group 1 followed by what you want to add after it. In the demo link https://regex101.com/r/gwcms1/1 you can see at the bottom how the result looks like after the replacements. – The fourth bird Apr 18 '20 at 07:17
  • @KotjengOren See this page for an example https://stackoverflow.com/questions/29809811/c11-regex-digit-after-capturing-group-in-replacement-string – The fourth bird Apr 18 '20 at 07:22