1

I need help with my C++ code.

I want to search a file and read it line by line and if the parent of a phone number matches it must print that line to another file.

I am able to match a string but not sure : How to match a format/pattern of a phone number Phone numbers can be different. I just want to follow the format of phone number match.

Example of Number can be xx-xxx-xxxx

This is my code take a look

// reading a text file

         if (mywritingfile.is_open())
         {

                  //Getting data line from file.
              while ( getline (myfile,line) )
            {

                 if (Match the Pattren from the line)//Need Help Here.
                 {   
                     //Printing the Mached line Content Of the source File to the destination the File.
                     //Output Every line that it fetches
                     cout << line << endl;
                     mywritingfile << line << endl;
                     matches++;   
                 }
            }
         }
4

1 回答 1

5

有一个简短的示例如何使用正则表达式(C++ 11)。

#include <iostream>
#include <regex>

int main()
{
  std::regex r("[[:digit:]]{2}-[[:digit:]]{3}-[[:digit:]]{4}");

  std::string s1("12-311-4321");
  std::string s2("112-311-4321");

  if (std::regex_match(s1, r)) {
    std::cout << "ok" << std::endl;
  } else {
    std::cout << "not ok" << std::endl;
  }

  if (std::regex_match(s2, r)) {
    std::cout << "ok" << std::endl;
  } else {
    std::cout << "not ok" << std::endl;
  }

    return 0;
}

您需要做的就是使用std::regex_match函数检查每一行。

于 2013-11-10T18:36:18.483 回答