2013-01-04 29 views
0

我目前有以下正则表达式来解析数据。而“排除”添加一个排除到正则表达式

$userNameArray = (userName1, user Name2, User Name 3); 

$re = '/^(?<timeMined>[0-9]{2}:[0-9]{2}:[0-9]{2}) # timeMined 
    \s+ 
    (?<userName>[\w\s]+)  # user name 
    \s+(?:has\s+looted)\s+ # garbage text between name and amount 
    (?<amount>\d+)    # amount 
    \s+x\s+      # multiplication symbol 
    (?<item>.*?)\s*$   # item name (to end of line) 
    /xmu'; 
preg_match_all($re, $sample, $matches, PREG_SET_ORDER); 
foreach ($matches as $value){ 
    code 
} 

我的代码的数组目前有一个if语句,如果$value['userName']$userNameArray执行的代码的一部分,如果没有,做了不同的部分。然而,如果我只是在正则表达式中解析不好的用户,这会更容易。

+0

把它留给你的应用程序,不要把它放在正则表达式中。顺便说一句,这并不容易。如果你想分享你的代码,你的实际问题可能会变得可见,并且可能会给你更好的建议,然后将用户名编码成正则表达式模式。你在这里听起来像一个标准的过滤器操作,你应该避开字符串解析。 – hakre

回答

2

虽然你可以使用negative lookahead作为

$re = '/^(?<timeMined>[0-9]{2}:[0-9]{2}:[0-9]{2}) # timeMined 
    \s+ 
    (?!user1|user2|user3)  # exclude users <-- 
    (?<userName>[\w\s]+)  # user name 
    \s+(?:has\s+looted)\s+ # garbage text between name and amount 
    (?<amount>\d+)    # amount 
    \s+x\s+      # multiplication symbol 
    (?<item>.*?)\s*$   # item name (to end of line) 
    /xmu'; 

会显著应用程序逻辑编码成正则表达式。最有可能的是,您当前的解决方案更易于理解,更具可读性且更易于更改。

+0

硬编码用户正确吗?它不会将它们拉出阵列。 – mhopkins321