Home > Enterprise >  Having trouble inserting backslashes into a string
Having trouble inserting backslashes into a string

Time:12-17

For example, I have a line like this:

abc prt[67][2]

I need to insert backslashes into this line in this way:

abc prt\[67\]\[2\]

So basically, whenever [somenumber] occurs in the lines of the file, I need to convert it to \[somenumber\]

Have tried this, but I'm sure its wrong because it's not working.

$line =~ s{[(\d )}{\\[$1]}g;

Can anyone help me with this?

CodePudding user response:

You need to escape the 1st bracket and include the 2nd bracket in the pattern side of the substitution:

use warnings;
use strict;

while (my $line = <DATA>) {
    $line =~ s{\[(\d )]}{\\[$1\\]}g;
    print $line;
}

__DATA__
abc prt[67][2]
foo[0]

Prints:

abc prt\[67\]\[2\]
foo\[0\]

CodePudding user response:

You can match

(?<!\\)\[\d (?=])

The pattern matches:

  • (?<!\\) Negative lookbehind, assert not already a \ directlyt to the left
  • \[ Match [
  • \d Match 1 digits
  • (?=]) Postive lookahead, assert ] directly to the right

And replace with the full match between backslashes.

Regex demo

use strict;
use warnings;

my $line = 'abc prt[67][2]';
$line =~ s/(?<!\\)\[\d (?=])/\\$&\\/g;
print $line

Output

abc prt\[67\]\[2\]

CodePudding user response:

You can do:

echo 'abc prt[67][2] [no number]' | perl -lpE 's/(\[)(\d )(\])/\\\1\2\\\3/g'
abc prt\[67\]\[2\] [no number]

Just don't get lost in all the backslashes.

CodePudding user response:

A few additions are needed:

$line =~ s{\[(\d )\]}{\\[$1\\]}g;
#          ^      ^^       ^^

Notably, [ and ] need to be escaped in the pattern because they have a special meaning otherwise.


You asked to escape the [ and ] that enclose "numbers".

Have you considered escaping all [ and ]?

$line =~ s{([\[\]])}{\\$1}g;

Have you considered escaping all non-word characters?

$line =~ s{(\W)}{\\$1}g;

or

$line = quotemeta($line);
  • Related