regex - How to replace single quote to two single quotes, but do nothing if two single quotes are next to each other in perl -
i need change single quote found in string 2 single quotes, if more 1 single quotes found successively, should remain is.
e.g. str = abc'def''sdf'''asdf output should : str = abc''def''sdf'''asdf
i think cleanest way search following pattern:
(?<!')'(?!')
and replace 2 single quotes. pattern searches single quote, has negative lookbehind , lookahead assertions check preceeding , proceeding character not single quote.
my $var = "abc'def''sdf'"; print "$var\n"; $var =~ s/(?<!')'(?!')/''/g; print "$var\n";
note have written straight pattern match, e.g.
(^|[^'])'($|[^'])
but replacement becomes tricky because have consumed characters surrounding single quote. don't work if don't have to.
output:
abc'def''sdf' abc''def''sdf''
demo here:
Comments
Post a Comment