简体   繁体   中英

Perl regex - match the previous character

I want to be able to do a regex on a string to add a backslash before a double quote, only when it doesn't already have a backslash before it. So the function (eg regex_string) would have the output -

$my $string_1 = 'A "sentence';
regex_string($string_1); # Would equal 'A \"sentence'.  A backslash was added as one was not present.

$my $string_2 = 'A \"sentence';
regex_string($string_1); # Would equal 'A \"sentence'.  A backslash is not added because one already existed.

Can anyone help with how the regex should look? Thanks

The below regex would match all the double quotes " which are not preceded by a backslash. Replacing the matched double quotes with \\\\" will give you the desired output.

Regex:

(?<!\\)(")

Replacement string:

\\\1

DEMO

#!/usr/bin/perl
use strict;
use warnings;

my @strings = ('A "sentence', 'A\"sentence', '"A sentence');

for my $str(@strings) {
    $str =~ s/(?<!\\)(")/\\$1/g; 
    print $str, "\n";
}

Or the regex line would be like $str =~ s/(?<!\\\\)"/\\\\"/g;

Output

A \"sentence
A\"sentence
\"A sentence

The regular expresion maybe: s/[^\\\\]"|^"/\\\\"/g . It looks for any character different of \\ preceding the "

use strict;
use warnings;

my @strings = ('A "sentence', 'A\"sentence', '"A sentence');

for my $str(@strings) {
    $str =~ s/[^\\]"|^"/\\"/g; 
    print $str, "\n";
}

Prints:

A\"sentence
A\"sentence
\"A sentence

它将\\放在"之前,并且反斜杠尚未到位,

$string =~ s|(?<! \\)(?= ")|\\|xg; 
\\"|"

You can try this.

Replace by

\\\\"

See demo.

http://regex101.com/r/bZ8aY1/4

Can a backslash escape itself?

Therefore the string A \\\\"sentence needs to have an additional backslash to escape the double quote?

If so, then the following implementation would work:

use strict;
use warnings;

while (my $str = <DATA>) {
    $str =~ s/\\.(*SKIP)(*FAIL)|(?=")/\\/g; 
    print $str;
}

__DATA__
A "sentence
A\"sentence
"A sentence
A \\"sentence
A \\\"sentence

Outputs:

A \"sentence
A\"sentence
\"A sentence
A \\\"sentence
A \\\"sentence

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM