Perl: Escape special chars in a string to match a regex -
I'm writing bash functions to handle string operations with regexes The built-in works are very bad in the job, I am using perl command to do this. For example, here's my "Stretch" function (in the Bash):
#Usage: If (strMatch & lt; string & gt; Lt; regex & gt;); Then ... function strMatch {local str = "$ 1" local regex = "$ 2" local perlCmd = 'if (qq (' $ str ') = ~ m /' $ regex '/ g) {print "0" ; } Other {print "1"; } 'Refund $ (perl -e "$ perlCmd")}
Test string: foo-bar \ rLoading ... xx% \ rFile: "Some- (filename. Ext ".
regex: -bar (?:. *?) File:". (* * *) \ .ext "
All Except for a few things, works fine, I can not find any way to avoid special characters inside the string (for some of them, at least).
I am very new in Perl (regex syntax Except)), so I tried and tried successfully without many things here. '' Qq ' with a
, which is interpreted as a capturing group) is a' mail '. I guess that' '[' ... ']
what will happen with ... & nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; => -e syntax error line 1, "cq (af-bar \ r loading ... xx% \ rFile:" some- (filename.ext ".) = ~ M / -bar \ r (? :. *?) File: "(. *.) \ .ext" / g) {"
& nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; => String terminator can not be found ")" Eoff Anywhere - E Line 1.
with 'quotemet A' This is bad, but it breaks: ','% ',' \ R '... too much everything
& nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; ; => Backslash found, where "bar" is expected - operator A on line 1
& nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; & Nbsp; =>% Operator or semicolon missing
As a bonus, if I add 'w' or 'w' option to get Pearl warnings, then it does not print anything !! ! What is happening?
I just want to be able to include the string '%', '(', '[', '\ r', '\ n' ... in any way How to do that? What am I doing wrong?
Edit: Answered
Thanks Choroba , use Karl Logic ARGV works like a charm. I have also used a modified version of the solution for Ikygami which is more elegant.
The function now happens:
Local regex = "$ 2" local perlCmd = 'exit 1 if ($ ARGV [0]! ~ M / $ ARGV [1] / g)' perl -e '$ perlCmd "" "$ str" "$ regex" $ Returned?}
Edit 2: added to stop processing options.
string and regex as parameter (I also simplify the Perl code):
#! / Bin / bash # Usage: if (strMatch & lt; stri ng> & lt; regex & gt;); Then ... function strMatch () {local str = "$ 1" local regex = "$ 2" local perlCmd = 'print $ ARGV [0] = ~ m / $ ARGV [1] /? Test with code: 0: 1 'return $ (Perl-A "$ perl CMD" "" $ str "" $ regex ")}
~ / test.sh $ 'foo-bar \ r Loading ... xx% \ rFile: "some- (filename.ext"' '-bar (?:. *?) File: "( . *?). Ext ''
Comments
Post a Comment