How to extract a number from an almost random string in C ++ using regular expressions [closed]

3

How to extract a specific number from a string that can have almost any shape, I explain:

My string can be: cualquiercosa+CH+number+cualquiercosa that is: TEST-13?:41CH12f:A1345

I just need to extract the number that follows CH and convert it to int .

    
asked by user2357667 19.01.2017 в 12:17
source

1 answer

2

The format of the string seems quite closed despite the randomness of it, the following expressions can help you to extract the number:

  • .+CH(\d+).+ .
  • \w+-\d+\?:\d+CH(\d+)f:.+ .

Depending on how restrictive you want to be, you should use one or the other.

Apply regular expression to text.

The header <regex> added to C ++ in the C ++ 11 standard automates the process of using expressions Regular:

std::regex expresion(R"(\w+-\d+\?:\d+CH(\d+)f:.+)");
std::cmatch coincidencias;
std::regex_search(texto, coincidencias, expresion);

After the call to std::regex_search the object std::cmatch (which is a version of std::match_result for character strings char ) will contain the captured text of the regular expression, the first being capture in position 1.

Transform text to number.

You can use the std::atoi function in the header <cstdlib> :

int numero = std::atoi(coincidencias[1].str().c_str());

The std::atoi function expects to receive a pointer to a string of characters. The bracket operator ( [] ) of the object std::match_result returns an object sub_match that has a function to convert to std::string .

But I prefer the option to use a text stream :

std::stringstream stream(coincidencias[1].str());
int numero = 0;
stream >> numero;

Code.

[Here] you can see the code working:

int main()
{
    constexpr char text[]{"TEST-13?:41CH12f:A1345"};
    std::regex expresion(R"(\w+-\d+\?:\d+CH(\d+)f:.+)");
    std::cmatch coincidencias;
    std::regex_search(text, coincidencias, expresion);

    std::stringstream stream(coincidencias[1].str());
    int numero = 0;
    stream >> numero;
    std::cout << numero;
    return 0;
}
    
answered by 19.01.2017 в 17:05