You are not logged in.

#1 2014-07-31 15:11:12

snack
Member
From: Italy
Registered: 2009-01-13
Posts: 876

Inserting slashes in C++ strings

I'm writing a tiny routine to convert glob expressions into regular expressions. For that I need to escape each "." character in the glob string. Currently I'm doing like this:

regExpFiles.replace(pos, 1, "\\.");

where pos is the position of the "." character inside the string (previously found with string::find). Doing in this way I get two slashes in the regula expression string, i.e. "." is replaced by "\\.".  If I use only one slash in my replacement expression:

regExpFiles.replace(pos, 1, "\.");

I get a warning about an unrecognized escape sequence, and "." remains ".". With three slashes, same warning and a resulting "\\.". With four slashes, no warning and a resulting "\\\\."

Maybe I'm a dummy but I tried every possible reasonable combination of slashes in the definition of the replacement string so I believe that at least one of them should work as I desire... is there a way to obtain a single slash (or more generally: an odd number of slashes)? By the way, string::append show the same behavior.
Thanks.

Offline

#2 2014-07-31 16:49:28

aoba
Guest

Re: Inserting slashes in C++ strings

Best guess is that you're doing the replacement twice.  Does the following work as expected?

#include <iostream>
#include <string>


int main()
{
	std::string s = "This is a test.";
	std::cout << s.length() << ": " << s << std::endl;

	std::string::size_type pos = s.find('.');
	s.replace(pos, 1, "\\.");

	std::cout << s.length() << ": " << s << std::endl;

	return 0;
}

#3 2014-08-01 09:44:18

snack
Member
From: Italy
Registered: 2009-01-13
Posts: 876

Re: Inserting slashes in C++ strings

This is weird. The example of aoba works as expected but debugging with gcc inside Eclipse shows the incorrect behavior that I reported on the first post. In other words, on standard output I get "This is a test\." while gdb shows "This is a test\\.". I previously didn't try to print my results but only checked with gdb, so that's why I thought there was an error.  Anyway, is there a reason why gdb reports a different value for the string? Or is it just a bug?

Offline

#4 2014-08-01 11:37:37

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 30,332
Website

Re: Inserting slashes in C++ strings

 std:count << "a string\\." << std::endl;

will print

a string\.

One is the contents of the string variable, the other is what is displayed on screen when that variable is printed.


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#5 2014-08-01 11:43:09

snack
Member
From: Italy
Registered: 2009-01-13
Posts: 876

Re: Inserting slashes in C++ strings

Correct. I didn't think about it. Thanks for the clarification, Trilby.

Offline

Board footer

Powered by FluxBB