Below is my code

string str2 = "1, 2, 3, 4, 5, 6, 7, 8";
string output;  
typedef std::tr1::sregex_token_iterator sti;  
const sti end;  
for(sti i(str2.begin(), str2.end(), regex(",\\s"), -1); i != end; ++i)  
{
  //output += "\"" + *i + "\", ";
  output += "\"";
  output += *i;
  output += "\", ";  
}      
cout<<output.substr(0, output.length() - 2)<<endl;

the result is

"1", "2, 3, 4, 5, 6, 7, 8"

But what I expected was

"1", "2", "3", "4", "5", "6", "7", "8"

How could I solve the problems?
Thanks a lot

ps:i am using the <regex> library of visual c++ 2008

Recommended Answers

All 5 Replies

After a lot of struggles, I found out the problems
change

for(sti i(str2.begin(), str2.end(), regex(",\\s"), -1); i != end; ++i)

to

regex r(",\\s");
for(sti i(str2.begin(), str2.end(), r, -1); i != end; ++i)

never use temporary regex

Please mark as solved.

Now I have another question

string s = "point(1,1,:)=[303 225 1];point(2,5,:)=[238,121,1];";
  regex pattern("((\\d+)\\s(\\d+)\\s(\\d+)|(\\d+),(\\d+),(\\d+))");
  const sregex_token_iterator end;
  std::vector<int> v;
  v.push_back(2);
  v.push_back(1);
      
  for(sregex_token_iterator i(s.begin(), s.end(), pattern, v); i != end; )
  {
    cout<<*i++;
    cout<<" "<<*i++<<endl;
  }    
  cout<<endl;

I hope the output could be

225 303
121 238

But the results are totally wrong
How could I solve the problems?
Thanks a lot

PS:

regex pattern("(\\d+),(\\d+),(\\d+)");

or

regex pattern("(\\d+)\\s(\\d+)\\s(\\d+)");

are fine, but they would only output "225 303" or "121 238"

Sorry but, how to mark as solved?
Thanks

What is the wrong result you are getting? Please tell us as much as you can about what is wrong and we will be able to help you more easily.

PS. To mark as solved: just above the reply box at the bottom of the thread will be a bit about the thread being solved. It's easy enough to do when you look in the right place :)

The wrong results are

303 303 225 1
238, 121,1

I have no idea what is happening
Thanks a lot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.