Last active
November 22, 2017 12:50
-
-
Save Akdeniz/f075e1fdd5d3d2e0c643e4e4fd1da1db to your computer and use it in GitHub Desktop.
simple CPP regex examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <regex> | |
#include <sstream> | |
int main() | |
{ | |
std::string str = "[A,B,15] [C,D,1] [C,D,2][G,H,9] [C,D,a] [C,D,9] [E,F,00177] "; | |
std::regex word_regex( "\\[([A-Z]),([A-Z]),(\\d+)\\]" ); | |
// get words and check if each of them matches the regex | |
{ | |
std::istringstream iss( str ); | |
while ( iss.good() ) | |
{ | |
std::string word; | |
iss >> word; | |
std::smatch match; | |
if ( std::regex_match( word, match, word_regex ) ) | |
{ | |
int length = 0; | |
std::istringstream decimal_ss( match[3] ); | |
decimal_ss >> length; | |
std::cout << "from : " << match[1] << ", to : " << match[2] << ", length : " << length << std::endl; | |
} | |
else | |
{ | |
std::cout << "\"" << word << "\" does not match." << std::endl; | |
} | |
} | |
} | |
// outputs | |
// | |
// from : A, to : B, length : 15 | |
// from : C, to : D, length : 1 | |
// "[C,D,2][G,H,9]" does not match. | |
// "[C,D,a]" does not match. | |
// from : C, to : D, length : 9 | |
// from : E, to : F, length : 177 | |
// "" does not match. | |
// prints all matched parts | |
{ | |
for ( auto it = std::sregex_iterator( str.begin(), str.end(), word_regex ); it != std::sregex_iterator(); ++it ) | |
{ | |
const auto& elem = *it; | |
std::cout << "from : " << elem[1] << ", to : " << elem[2] << ", length : " << std::stoi( elem[3] ) << std::endl; | |
} | |
} | |
// outputs | |
// | |
// from : A, to : B, length : 15 | |
// from : C, to : D, length : 1 | |
// from : C, to : D, length : 2 | |
// from : G, to : H, length : 9 | |
// from : C, to : D, length : 9 | |
// from : E, to : F, length : 177 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment