How do you match \'

Viewed 118

I need a regex to match \' <---- literally backslash apostrophe.

my $line = '\'this';
$line =~ s/(\o{134})(\o{047})/\\\\'/g;
$line =~ s/\\'/\\\\'/g;
$line =~ s/[\\][']/\\\\'/g;
printf('%s',$line);
print "\n";

All I get out of this is

'this

When what I want is

\\'this

This occurs whether the string is declared using ' or ". This was a test script for tracking down a file parsing bug. I wanted to confirm that the regex was working as expected.

I don't know if when the backslash apostrophe is parsed by the regex it is not treated as 2 characters, but is instead treated as an escaped apostrophe.

Either way. what is the best way to match \' and print out \\'? I don't want to escape any other back slashes or apostrophes and I can't change the text I am parsing, just the way it is handled and outputted.

3 Answers
s/\\'/\\\\'/g

All three of your patterns match a backslash followed by a quote, the above being the simplest.

Your testing was in vain because your string doesn't contain any backslashes. Both string literals "\'this" (from earlier edit) and '\'this' (from later edit) produce the string 'this.

say "\'this";   # 'this
say '\'this';   # 'this

To produce the string \'this, you could use either of the following string literals (among others):

"\\'this"
'\\\'this'
say "\\'this";    # \'this
say '\\\'this';   # \'this

The answer is, of course

s/[\\][']/\\\\'/g

This will match

\'this

And substitute with this

\\'this

This was the only way I could get it to work.

Perl

Too much "regexing" in your snippet. Try:

my $line = '\'this';
$line =~ s/'/\\\\\'/g;
printf('%s',$line);
print "\n";

# \\'this

or... if you want another mode:

my $line = '\'this';
$line =~ s/'/\\'/g;
printf('%s',$line);
print "\n";

# \'this
Related