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其中执行部分代码,如果不是,则执行不同的部分。但是,如果我可以在正则表达式中解析出不良用户,这将变得容易得多。

4

1 回答 1

2

虽然您可以使用负前瞻,如

$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';

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

于 2013-01-04T23:02:33.863 回答