2015-11-03 25 views
0

我有一个数组填充数据库字段名,我运行grep命令来删除不需要的字段。在代码中看起来很丑,但它非常有用,因为我们可以很容易地看到数据库中哪些字段没有传递给另一个程序。 grep命令不喜欢我的回车,并且在CR之后立即忽略该字段。有很多丑陋的方法可以解决这个问题,还有很多复杂的方法,我在谷歌上看到,但是没有办法忽略greps“//”中的CRs?我真的很感谢你们看看这个。如何让Perl正则表达式更具可读性?

@fieldNames = grep ! /dbid|history|RecordID|CCObjects|MergeSWCRs|AssociatedIntegrationSet|Level1TestResults| 
        Level2TestResults|Level3TestResults|Level4TestResults|Reviews|WithdrawCR| 
        AssociatedWithdrawnCR|Attachments|AssociatedPRs|OriginatingSolution|AssociatedSWRsFull| 
        AssociatedSWRsDelta|ClonedFrom|ClonedTo|AssociatedComment|ExternalLinks|ratl_mastership/, @fieldNames; 

回答

2

使用/x modifier让你的正则表达式更具可读性和忽略空白。

即:

@fieldNames = grep ! 
    /dbid|history|RecordID|CCObjects|MergeSWCRs|AssociatedIntegrationSet|Level1TestResults| 
    Level2TestResults|Level3TestResults|Level4TestResults|Reviews|WithdrawCR| 
    AssociatedWithdrawnCR|Attachments|AssociatedPRs|OriginatingSolution|AssociatedSWRsFull| 
    AssociatedSWRsDelta|ClonedFrom|ClonedTo|AssociatedComment|ExternalLinks|ratl_mastership/x, 
    @fieldNames; 

或许略微优化:

my @fieldNames = 
    grep !/
     dbid| 
     history| 
     RecordID| 
     CCObjects| 
     MergeSWCRs| 
     Level[1-4]TestResults| 
     Reviews| 
     WithdrawCR| 
     Associated(?:WithdrawnCR|PRs|SWRsFull|SWRsDelta|Comment|IntegrationSet)| 
     Attachments| 
     OriginatingSolution| 
     Cloned(?:From|To)| 
     ExternalLinks| 
     ratl_mastership 
    /x, 
    @fieldNames; 
+2

你在跟我开玩笑。一个“x”?我只是试了一下,它完美的工作。我将阅读您发布的整个链接。非常感谢你。太酷了! – Matt

+0

不客气。 – TLP

+0

@Matt ...如果你正在研究正则表达式,http://perldoc.perl.org/perlretut.html绝对值得一读。 – stevieb

4

不要使用正则表达式:

my %ignored = (
    dbid  => 1, 
    history => 1, 
    RecordID => 1, 
    CCObjects => 1, 
    # ... 
); 

# or define the hash this way, if you prefer 
# my %ignored = map { $_ => 1 } qw(dbid history RecordID CCObjects ...); 

@fieldNames = grep { !$ignored{$_} } @fieldNames; 
+0

马特J,这真棒谢谢你。但是你为什么不喜欢我正在做的事情的正则表达式?我很认真地问,因为我是PERL的新手。我使用的正则表达式使用更少的可读行来完成同样的事情。但这可能会更快....我现在要去计时。非常感谢你回答我的问题。我希望我有一盎司的智力。 – Matt

+1

我喜欢正则表达式,但我只是喜欢在需要时使用它们。 Perl程序员倾向于使用正则表达式来处理所有事情,但有时您只需要一个简单的字符串匹配(这也应该快几个微秒)。 –

+0

这是有道理的,我接近我的代码改变尝试。真的很感谢你的建议和知识。 – Matt