2013-10-19 44 views
0

我有以下字符串:可选防止通配符结束的字符串被匹配

12345 This could be anythingREMOVE 

我需要匹配12345This could be anything。不幸的是,我需要解析的格式在该行末尾有一个字符串,并不总是存在(在本例中为REMOVE)。如何在没有REMOVE的情况下与我所寻找的相匹配?我尝试了以下模式:

^(\d{5}) (.*)(?:REMOVE|$) 

不幸的是,REMOVE由通配符回升:

(
    [0] => Array 
     (
      [0] => 12345 This could be anythingREMOVE 
     ) 

    [1] => Array 
     (
      [0] => 12345 
     ) 

    [2] => Array 
     (
      [0] => This could be anythingREMOVE 
     ) 

) 

回答

1

你可以试试这个正则表达式:

^(\d{5})((?:.(?!REMOVE))+.) 

如何使用

  1. ^(\d{5}) - 比赛开始的字符串,之后为五数字[0-9]。一组圆括号用于捕获匹配的文本。
  2. ((?:.(?!REMOVE))+ - 匹配任何字符,如果没有立即跟上sedence REMOVE一次或多次。它停在nanything。它不能匹配g因为后跟REMOVE

  3. .) - 允许g匹配。

+1

这完美的作品!谢谢。 – Brad

+0

不客气! –

2

如果最后一个字符串REMOVE是可选的,那么为什么不能用使用正则表达式htis:

"/^(\d{5}) /" 

但是,如果你真的想避免REMOVE匹配模式,然后使用这个:

$s = '12345 This could be anythingREMOVE'; 
if (preg_match("/^(\d{5}) (.*?)(?:REMOVE|)$/", $s, $arr)) 
    var_dump($arr); 

输出:

array(3) { 
    [0]=> 
    string(34) "12345 This could be anythingREMOVE" 
    [1]=> 
    string(5) "12345" 
    [2]=> 
    string(22) "This could be anything" 
} 
+0

我需要匹配“这可能是任何东西”以及。有时它最后有'REMOVE',有时它没有。无论哪种方式,我都不想在比赛中使用REMOVE。 – Brad

+0

好吧,现在检查编辑后的代码。 – anubhava

+0

谢谢@anubhava。如果我按照原样使用第二行,那么“这可能是任何事情”都不匹配。如果我将它修改为'^(\ d {5})(。*)(?=(?: REMOVE)?)$',索引2仍然包含'This might be anythingREMOVE'。 – Brad