2012-06-21 59 views
0

嘿,這應該是簡單的,我只是沒有看到它,我想創建一個正則表達式(PERL,Awk,SED/* nix下可用),它會找到領先的現金($),下一個Equal(=),並且處理介於雙引號或單引號的第一個實例與最後一個雙引號或單引號之間的內容。正則表達式在兩個條件後運行

讓我舉幾個例子。

$this = 'operate on some text in here'; # operates between single quotes 
$this = "operate on some text in here"; # operates between double quotes 
$this = 'operate "on some text" in here'; # operates between single quotes 
$this = 'operate \'on some text\' in here'; # operates between outer single quotes 

我嘗試了一些非常糟糕的正則表達式。但只是無法讓它匹配正確。

這裏就是我將其插入,在感興趣的

printf '$request1 = "select * from whatever where this = that and active = 1 order by something asc";\n' | 
grep '{regex}' * | 
perl -pe 's/select/SELECT/g ; s/from/\n FROM/g ; s/where/\n  WHERE/g ; s/and/\n  AND/g ; s/order by/\n   ORDER BY/g ; s/asc/ASC/g ; s/desc/DESC/g ;' | ## enter through file with all clauses 
awk '{gsub(/\r/,"");printf "%s\n%d",$0,length($0)}' ## take first line convert to whitespace, use on following lines 

謝謝你們任何人的情況下!

回答

2

腳本:

@list = <main::DATA>; 

foreach (@list) { 
    my @x = /^\s*\$(\S+)\s*=\s*(['"])((?:.(?!\2)|\\\2)*.?)\2\s*;/; 
    $x[2] =~ s/\\$x[1]/$x[1]/g; # remove backslash before quote character 
    print "$x[0]\t$x[2]\n"; 
} 

__DATA__ 
$this = 'operate on some text in here';  // operates between single quotes 
$this = "operate on some text in here";  // operates between double quotes 
$this = 'operate "on some text" in here'; // operates between single quotes 
$this = 'operate \'on some text\' in here'; // operates between outer single quotes 

會給你:

this operate on some text in here 
this operate on some text in here 
this operate "on some text" in here 
this operate 'on some text' in here 
+0

我不想要這個或其他任何var在引號之前,儘管是一個該死的好回答 – ehime

+0

@ehime - if你只需要等式的正確部分,然後將'print'改爲'「$ x [2] \ n」'。 –

+0

我該如何運行/結合我的當前代碼? – ehime

5

通常,如果你解析實際的Perl代碼,我會建議(並使用)PPI。否則,只要使用Regexp::Common

use Regexp::Common; 

my @lines = split /\s*\n\s*/, <<'TEST'; 
$this = 'operate on some text in here'; // operates between single quotes 
$this = "operate on some text in here"; // operates between double quotes 
$this = 'operate "on some text" in here'; // operates between single quotes 
$this = 'operate \'on some text\' in here'; // operates between outer single quotes 
TEST 

for (@lines) 
{ 
    /$RE{quoted}{-keep}/ && print $1, "\n"; 
} 

給出:

$ perl x.pl 
'operate on some text in here' 
"operate on some text in here" 
'operate "on some text" in here' 
'operate \'on some text\' in here' 
+0

@ZnArK - 如果你要「修理」我的代碼,第一個測試你的修復。它甚至不接近產生正確的輸出。您還會注意到我顯示了原始代碼的輸出,這表明代碼中沒有錯誤。 (那些批准你的編輯也沒有測試它。)我已被迫恢復它以保持它的正確性。 – Tanktalus

+0

@Tanktalus我沒有爲你調試你的代碼,只修復了這些註釋,以便格式正確。是否正確註釋Perl的註釋? – ZnArK

+0

@Tanktalus我現在看到爲什麼這個工程。猜猜美化不正確解釋perl .... – ZnArK

0

這可能會爲你工作:

sed 's/\(\$[^=]*=[^'\''"]*\)\(['\''"]\)[^\\'\''"]*\(\\['\''"][^'\''"]*\)*\2/\1\2Replacement\2/' file