Vishwas
Vishwas

Reputation: 35

Regular expression in c++ for searching string pattern

I have a string like this:

string s ="one 1 two 2 three 3";

I want to write a regular expression such that when the user inputs "one" i should print 1, if the input given as "two"...any suggestions or help would greatly appreciated.

Upvotes: 0

Views: 2141

Answers (2)

Shakiba Moshiri
Shakiba Moshiri

Reputation: 23794

very easy:

std::string s = "one 1 two 2 three 3";

std::regex rx( "([a-z]+) (\\d+)" );
std::match_results< std::string::const_iterator > mr;

std::regex_search( s, mr, rx );
std::cout << mr.str( 1 ) << '\n';  // one
std::cout << mr.str( 2 ) << '\n';  // 1  

and for the whole match:

std::string temp = s;
while( std::regex_search( temp, mr, rx ) ){
    std::cout << mr.str( 1 ) << '\n';
    std::cout << mr.str( 2 ) << '\n';
    temp = mr.suffix().str();
}  

the output:

one
1
two
2
three
3

and eventually:

std::string ui; //user_input

std::string temp = s;
while( std::regex_search( temp, mr, rx ) ){

    std::getline( std::cin, ui );

    if( ui == mr.str( 1 ) ){
       std::cout << mr.str( 2 ) << '\n';
    }

    temp = mr.suffix().str();
}  

NOTE: this is not a perfect solution since regex_search match the items one by one. So you should enter one then two then three

test

 ideas $  ./temp 
one
1
two
2
three
3
 ideas $  

May as you want, but I put it just for learning to see how it works:

std::string s = "one 1 two 2 three 3";

std::string ui; //user_input
std::getline( std::cin, ui );

std::string pt = "(" + ui + ")" + " ";
std::regex rx( pt + "(\\d)" );
std::match_results< std::string::const_iterator > mr;

std::regex_search( s, mr, rx );
if( ui == mr.str( 1 ) ){
   std::cout << mr.str( 2 ) << '\n';
}   

test

 ideas $  ./temp
one
1
 ideas $  ./temp
two
2
 ideas $  ./temp
three
3
 ideas $  

Upvotes: 4

Bathsheba
Bathsheba

Reputation: 234695

Ditch the reg-ex. Write some code instead. Use something of the form

int main()
{
    std::map<std::string, int> m = {{"one", 1}, {"two", 2}, {"three", 3}};
    std::string input;
    std::cin >> input
    std::cout << m[input];
}

Note the fancy initialisation: valid from C++11 onwards.

Upvotes: 4

Related Questions