正则表达式在两个条件下运行

时间:2012-06-21 19:25:36

标签: regex perl sed awk

嘿伙计这应该很简单,我只是没有看到它,我想创建一个正则表达式(可在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

谢谢你们!

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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

答案 2 :(得分:0)

这可能对您有用:

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