0

嘿伙计们,这应该很简单,我只是没有看到它,我想创建一个正则表达式(在 PERL、Awk、SED / *nix 下可用),它将在找到领先的现金 ($) 后运行,下一个相等 (=) 并处理双引号或单引号的第一个实例与双引号或单引号的最后一个实例之间的内容。

让我举几个例子。

$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

多谢你们!

4

3 回答 3

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'
于 2012-06-21T19:38:37.670 回答
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
于 2012-06-21T21:08:37.717 回答
0

这可能对您有用:

 sed 's/\(\$[^=]*=[^'\''"]*\)\(['\''"]\)[^\\'\''"]*\(\\['\''"][^'\''"]*\)*\2/\1\2Replacement\2/' file
于 2012-06-21T21:13:58.767 回答