Question

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;
}
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top