[erlang-questions] Backslashing in re:replace

Robert Virding rvirding@REDACTED
Tue May 12 13:06:36 CEST 2009


Hi,

Erlang doesn't eat up the backslash character in strings, it is a quote
character which is used to put "special" characters in a string. For example
\t becomes a TAB and \n a newline character. \\ becomes simply the \
character.

This why the string "\\." becomes the regular expression '\.' and the string
"\\\\." becomes the string '\\.'.

I think the reason for this behaviour is that the underlying regular
expression implementation, PCRE, also uses the \ character as a quote
character in it's strings so your original replacement string '\.' is
interpreted as just a '.'. You therefore need an extra \ in the replacement
string which is why it must be "\\\\." in Erlang. You are getting a double
string treatment.

This is not the same in the regular expression as you have noted.

Again this straight off the top of my head but would explain the behaviour.

Robert

2009/5/12 Attila Rajmund Nohl <attila.r.nohl@REDACTED>

> Hello!
>
> I'd like to replace all dot characters in a string with backslash-dot
> sequences. My first try was
>
> re:replace("f.e.l.", "\\.", "\\.", [{return, list}, global])
>
> Because Erlang "eats up" the backslash characters, the actual regular
> expression in the second argument is "\." which is exactly what I
> want. For the same reason the actual replacement string is also "\."
> which is also what I want. However, the result is not what I expected:
>
> > re:replace("f.e.l.", "\\.", "\\.", [{return, list}, global]).
> "f.e.l."
>
> When I added a couple of more backslashes to the replacement string, I
> got what I wanted:
>
> > re:replace("f.e.l.", "\\.", "\\\\.", [{return, list}, global]).
> "f\\.e\\.l\\."
>
> but I don't understand why I need four backslashes instead of two. Any
> light on this issue?
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090512/9e495d2e/attachment.htm>


More information about the erlang-questions mailing list