1

This regex will trim the string at line breaks.
I want it to trim both end only and preserve any line breaks in the middle.

string s("     Stack \n Overflow    ");
boost::regex expr("^[ \t]+|[ \t]+$");
std::string fmt("");
cout << boost::regex_replace(s, expr, fmt) << endl;
ildjarn
  • 62,044
  • 9
  • 127
  • 211
user754425
  • 437
  • 1
  • 4
  • 10

1 Answers1

2

If you want to make the regular expression match at the beginning and the end of the input string(want to preserve spaces around the in-between \n), \A and \z instead of ^ and $ might meet the purpose.
For example:

boost::regex expr("\\A[ \t]+|[ \t]+\\z");
Ise Wisteria
  • 11,259
  • 2
  • 43
  • 26
  • This does not seem to produce consistent results. Try to parse this for example: string s(" Stack \n Overflow\r ") – user754425 May 19 '11 at 21:22
  • Could you tell the result you expect from that input? For example, it produced the result `"Stack \n Overflow\r"` in my environment. – Ise Wisteria May 19 '11 at 22:59
  • My bad. The expression I wanted you to test is this string s(" Stack \n Over\rflow "). The result I get is this Stack\n flowOver – user754425 May 19 '11 at 23:16
  • That produced `"Stack \n Over\rflow"` in my environment (the spaces around `\n` were preserved, and the spaces at the beginning and at the end were removed). If you mean `flowOver` is strange, probably the cause is `\r`(carriage return). Perhaps a code like `int main() { puts("Stack \n Over\rflow"); }` will produce the same output(that is, `regex` stuff is unrelated). If you mean totally different thing, could you tell the result you expect from that input? – Ise Wisteria May 19 '11 at 23:52
  • You are absolutely correct. The result you are getting is what I was expecting and that is what I get if I print the result to file as opposed to the console. Side note: I tried the same expression on std::tr::regex and the program crashed.( Windows VS 2008 express ) – user754425 May 20 '11 at 00:15
  • I see, glad the answer helped :-) – Ise Wisteria May 20 '11 at 10:24