0

Why this code does not replace the 'Mozilla/5.0' to 'My User Agent'?

The Regex works fine in Notepad++ but does not work in my console app.

#include <regex>
#include <string>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    string header = 
"GET / HTTP/1.1\r\n\
Host: com.com\r\n\
User-Agent: Mozilla/5.0\r\n\
Connection: keep-alive";

    tr1::regex rx("^(User-Agent:).+$", regex_constants::icase);
    header = regex_replace(header, rx, "$1 My User Agent", regex_constants::format_first_only);

    return 0;
}
6
  • What compiler are you using? regex C++11 was not fully supported until very recently. It may be that Notepad++ is using a different compiler from your console (this is in case you don't get a compilation error) Commented May 11, 2014 at 4:55
  • I use VS 2012. Platform Toolset: Visual Studio 2012 (v110) Commented May 11, 2014 at 4:57
  • Are you getting an error when compiling with VS? Or nothing happens? Commented May 11, 2014 at 4:59
  • No, no errors. But the header was not changed. Commented May 11, 2014 at 5:01
  • When you say "works fine in Notepad++", you mean you are compiling a program with Notepad++ and it works? Or you are using the regex in Notepad++? Commented May 11, 2014 at 5:17

1 Answer 1

5

The problem is that ^ means beginning of string, not beginning of line. You can use the following regex, which works fine:

((?:^|\r\n)User-Agent:).+(?=$|\r\n)

Regular expression visualization

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.