如何使用perl正則表達式從'abc'提取abc?如何提取一個在perl中用單引號括起來的字符串?
我試圖
echo "'abc'" | perl -ne 'if(/\'(.*)\'/) {print $1}'
,但它顯示 -bash:靠近意外的標記語法錯誤'(」
預先感謝您的回覆
如何使用perl正則表達式從'abc'提取abc?如何提取一個在perl中用單引號括起來的字符串?
我試圖
echo "'abc'" | perl -ne 'if(/\'(.*)\'/) {print $1}'
,但它顯示 -bash:靠近意外的標記語法錯誤'(」
預先感謝您的回覆
好了,廉價的方式是不用單引號括住你的perl語句:
echo "'abc'" | perl -ne "if(/'(.*)'/) {print $1}"
殼牌轉義爲奇數規則...
如果你真的想這樣做「正確」的方式,你可以結束你的第一個單引號字符,把在報價,並開始另一個問題:
echo "'abc'" | perl -ne 'if(/'\''(.*)'\''/) {print $1}'
這不是一個perl問題,這是一個shell問題:你不能在單引號中包含單引號。
您有'\''
替換每個單引號(單引號結束,躲過了單引號,勁兒行情的開始)
echo "'abc'" | perl -ne 'if(/'\''(.*)'\''/) {print $1}'
你需要逃避你單qoute「\」」
echo "'abc'" | perl -ne 'if(/'\''(.*)'\''/){print $1}'
你有一個shell引用問題,而不是Perl問題。
這是sed
一個良好的使用:
echo "'abc'" | sed "s/'//g"
choroba's answer解決了確切的問題。對於通用的解決方案,以任何引用問題,請String::ShellQuote:
$ alias shellquote='perl -E'\''
use String::ShellQuote qw(shell_quote);
local $/ = undef;
say shell_quote <>;
'\'''
$ shellquote
user input → if(/'(.*)'/) {print $1}␄
perl output → 'if(/'\''(.*)'\''/) {print $1}'
前面加上一個美元符號直接砸向你單引號Perl代碼使用alternate quoting method,輪流關閉shell擴展:
echo "'abc'" | perl -ne $'if(/\'(.*)\'/) {print $1}'
更多的解決方案發布在這裏[perl-one-liner-with-single-quote](http://stackoverflow.com/questions/5106097/perl-one-liner-with-single-quote) – jchips12 2012-01-04 17:50:13
@ jchips12 - 我喜歡解決方案'\ 047' – mob 2012-01-04 17:59:09