Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use 's///' if my string contains a '/'?

Tags:

perl

I'm using Perl 5.10.6 on Mac 10.6.6. I want to execute a simple search and replace against a file so I tried:

my $searchAndReplaceCmd = "perl -pi -e 's/\\Q${localTestDir}\\E//g' ${testSuiteFile}";
system( $searchAndReplaceCmd );

but the problem above is the variable $localTestDir contains directory separators ("/"), and this screws up the regular expression ...

Bareword found where operator expected at -e line 1, near "s/\Q/home/selenium"

Backslash found where operator expected at -e line 1, near "Live\" syntax error at -e line 1, near "s/\Q/home/selenium"

Search pattern not terminated at -e line 1.

How do I do a search and replace on a file when the variable in question contains regular expression characters? Thanks.

like image 397
Dave Avatar asked Aug 01 '11 13:08

Dave


People also ask

How do you check if a string contains a?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

How do you use contains in a string?

contains() method searches the sequence of characters in the given string. It returns true if sequence of char values are found in this string otherwise returns false. Here conversion of CharSequence to a String takes place and then indexOf method is called.

How do you check if a part of a string is a letter?

In order to check if a String has only Unicode letters in Java, we use the isDigit() and charAt() methods with decision-making statements. The isLetter(int codePoint) method determines whether the specific character (Unicode codePoint) is a letter. It returns a boolean value, either true or false.


1 Answers

It seems that $localTestDir has begins with a /.

Remedy by changing the regex delimiter to something other than /:

my $searchAndReplaceCmd = "perl -pi -e 's!\\Q${localTestDir}\\E!!g' ${testSuiteFile}";

From perldoc perlrequick :

$x = "A 39% hit rate";
$x =~ s!(\d+)%!$1/100!e;       # $x contains "A 0.39 hit rate"

The last example shows that s/// can use other delimiters, such as s!!! and s{}{}, and even s{}//. If single quotes are used s''', then the regex and replacement are treated as single-quoted strings.

like image 110
Zaid Avatar answered Oct 04 '22 02:10

Zaid