Avoid empty token in cpp

I have a line:

s = "server ('m1.labs.terada')ta.com') username ('user5') password('user)5') dbname ('default')"; 

I am retrieving the argument names: e.g. server, username ..., dbname.

To do this, I use the following regular expression:

 regex re("\\(\'[!-~]+\'\\)"); sregex_token_iterator i(s.begin(), s.end(), re, -1); sregex_token_iterator j; unsigned count = 0; while(i != j) { string str1 = *i; cout <<"token = "<<str1<< endl; i++; count++; } cout << "There were " << count << " tokens found." << endl 

For this, the output I get is:

 token = server token = username token = password token = dbname token = There were 5 tokens found. 

How can I avoid the formation of the 5th marker. Did I miss something?

+2
source share
1 answer

It turns out that at the end of the line there are some characters other than words. You can match them with \W* (zero or more characters without a word). Since your tokens consist only of the word characters, you can safely wrap your pattern with the \W* pattern:

 regex re("\\W*\\(\'[!-~]+\'\\)\\W*"); 

Watch the C ++ online demo

Result:

 token = server token = username token = password token = dbname There were 4 tokens found. 
+1
source

Source: https://habr.com/ru/post/1270132/


All Articles