簡體   English   中英

Perl正則表達式-匹配上一個字符

[英]Perl regex - match the previous character

我希望能夠對字符串進行正則表達式,以在雙引號之前添加反斜杠,僅當它之前沒有反斜杠時才可以。 因此該函數(例如regex_string)將具有輸出-

$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.

任何人都可以幫助您查找正則表達式嗎? 謝謝

下面的正則表達式將匹配所有的雙引號" ,其后沒有反斜杠。用\\\\"替換匹配的雙引號\\\\"將為您提供所需的輸出。

正則表達式:

(?<!\\)(")

替換字符串:

\\\1

演示

#!/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";
}

或正則表達式行就像$str =~ s/(?<!\\\\)"/\\\\"/g;

輸出量

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

在正規表示法可能: s/[^\\\\]"|^"/\\\\"/g ,它看重的是不同的任何字符\\之前的"

use strict;
use warnings;

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

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

印刷品:

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

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

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

你可以試試看

替換為

\\\\"

參見演示。

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

反斜杠可以自己逃脫嗎?

因此,字符串A \\\\"sentence需要有一個額外的反斜杠才能轉義雙引號嗎?

如果是這樣,那么以下實現將起作用:

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

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM