tags:

views:

62

answers:

2

Hello. I am using tinyperl with the following script:

@lines=<STDIN>;
foreach (@lines) {
    s/\\(.)/($1 eq '"' or $1 eq '\\') ? $1 : '\\' . $1/eg;
    print;
}

I would like each backslash to be considered only with the following character, and remove the backslash only if the following character is a double quote or another backslash. (I know this purpose might be unsound to you, but never mind).

For example, I would like to translate abc\ndef\\ghi\"\\\n to abc\ndef\ghi"\\n. But this script seems to translate it to abcndef\ghi"\n instead.

Could you help?

+4  A: 

Try

s/\\([\\"])/$1/g;

The [] gives a character class that matches either a backslash or a double quote so we are saying replace a backslash followed by either another backslash or double quote with whichever character in the character class matched.

mikej
won't this also remove my `backslash`or `"` along with the backslash? Also, will perl eat two characters each time he will encounter a backslash? (ps. markdown is sometimes a bit buggy)
Benoit
@Benoit You may have seen the very first version of my answer which was posted briefly before I edited it so that the second matching character is not removed. Please try with the revised solution and sorry for the confusion!
mikej
thank you. This works quite well!
Benoit
A: 

Looks like you want a look-ahead assertion (see the section in perlre on Extended Patterns).

s/\\(?=[\\"])//g;
davorg
I think this will replace \\\\\\a with \a only, because it does not eat up the second slash each time…
Benoit