0

I have strings that look like this for example subnet 1 ims-0-x ip address

and I want to get rid of the -x so it will be subnet 1 ims-0 ip address

I tried doing this regex replace

$string=~ s/\\-x//;

which is not working. I think my issue is that I am not escaping the dash properly. please help me fix that one line.

Nate
  • 1,889
  • 1
  • 20
  • 40
  • Please provide your exact code and also give exactly what is the output that you are getting. – shivams Jun 09 '15 at 21:33
  • `perl -e '$s="subnet 1 ims-0-x ip address"; $s =~ s/\-x//; print $s;'` works. If that's not the actual string you're using and is a fabricated/stripped example, please post the original string with perhaps the IPs changed. You could be getting caught up with what is contained in the original string. For example... if the "-x" actually contains special characters, you may not be escaping them properly. – stevieb Jun 09 '15 at 21:42
  • 3
    FYI: double-backslash in a regex is a literal blackslash (i.e. a literal backslash in the input) and `-` isn't special in this context: within a regex a hyphen is only special in between `[` and `]` (and only if it isn't first or last). – kjpires Jun 09 '15 at 22:47
  • it had one back slash escaping the dash, when i typed one back slash it did not show up on stackoverflow for some reason. so i typed two back slashes and then it only showed 1. but now i see two there.... not sure why. but yes its supposed to say s/\-x// ; – malika waller Jun 11 '15 at 13:38

2 Answers2

1

You are escaping a backslash and not the dash. With two backslashes (\\), the first backslash escapes the second and it looks for a backslash in the string. It should be s/-x//. You don't need to escape the -.

use strict;
use warnings;

my $s = "subnet 1 ims-0-x ip address";
$s =~ s/-x//;
print "$s\n"
ThisSuitIsBlackNot
  • 23,492
  • 9
  • 63
  • 110
Nate
  • 1,889
  • 1
  • 20
  • 40
  • I do not see any difference between your regex and one given in question. – shivams Jun 09 '15 at 21:34
  • I took out the first backslash that was escaping another backslash... Then in an edit I removed both backslashes because it isn't necessary to escape the dash... – Nate Jun 09 '15 at 23:16
0

I tried this and its working fine, /g is to replaceAll instances. The output is "subnet 1 ims-0 ip address"

$string = "vishwassubnet 1 ims-0-x ip address";
$string =~ s/-x//g;
print $string;

https://ideone.com/9zh91T

Vishwas
  • 506
  • 1
  • 5
  • 20