2015-02-10 41 views
0

我匹配数字和特定字符串之前的逗号的第一个匹配项。但是,我不想匹配某一组数字。在出现前匹配第一个不是特定数字的数字

让我们用一些例子开始

数字我不想匹配的:2013年,2014年,2015年

“这是1串在2013年我要匹配。”

preg_match('/([\d,]+)\D*I want to match/', $str, $match); 

需要符合:1

“这是1串我想匹配”

preg_match('/([\d,]+)\D*I want to match/', $str, $match); 

需要符合:1

“这是2012年我想匹配的1串“

preg_match('/([\d,]+)\D*I want to match/', $str, $match); 

需要符合:2012

我现在正则表达式工程实例1 & 3,但我需要添加例如2

回答

1

的附加功能,我建议你改变你的正则表达式如下图所示。

([\d,]+)(?:(?:2013|2014|2015)|\D)*I want to match 

,并从组索引你想要的串1

DEMO

说明:

  • ([\d,]+)这将捕获一个或多个数字或逗号。
  • (?:(?:2013|2014|2015)|\D)*匹配字符串20132015。它找到一个非数字字符,然后控制转移到OR部分旁边的模式,即\D,它匹配任何非数字字符)。整个群组使整个模式重复零次或多次后,

代码:

$str = <<<EOT 
This is the 1 string in 2013 I want to match. 
This is the 1 string I want to match 
This is the 1 string in 2012 I want to match 
EOT; 
preg_match_all('~([\d,]+)(?:(?:2013|2014|2015)|\D)*I want to match~', $str, $match); 
print_r($match[1]); 

输出:

Array 
(
    [0] => 1 
    [1] => 1 
    [2] => 2012 
) 
+0

是的,谢谢。 – 2015-02-10 15:04:40

+0

你可以简单添加如何使用php匹配所有匹配项吗?这个preg_replace_all正则表达式返回空。 – 2015-02-10 16:55:26

+0

使用preg_match_all函数.. – 2015-02-10 16:56:48

0

你可以使用这个表达式

/(?:([\d,]+)\D*201[3-5]|([\d,]+))\D*I want to match/ 

Online demo

指令:

preg_match('/(?:([\d,]+)\D*201[3-5]|([\d,]+))\D*I want to match/', $str, $match); 
相关问题