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.
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.
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.
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.
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 ass!!!
ands{}{}
, and evens{}//
. If single quotes are useds'''
, then the regex and replacement are treated as single-quoted strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With