1

For some reason my regex is matching what I am after and extra. I am needing to just match the group #, but it's matching the first number of the phone numbers also.

Example data:

id: N group: 1 category: NAMES : Mike
id: N group: 2 category: NAMES : Seth
id: # group: 1 category: PHONE : 123-456-789
id: # group: 2 category: PHONE : 111 111-1111
id: @ group: 1 category: EMAIL : mike@mail.com
id: @ group: 2 category: EMAIL : seth@yahoo.com

Regex

preg_match_all('/:\s+\d/', $data, $matches);

Current output

1
2
1
1
2
1
1
2

Expected output

1
2
1
2
1
2
4

3 回答 3

3

通过更改您的正则表达式

"/group:\s*(\d+)/i"

问题是您在 PHONE 和 EMAIL 之后还有“:”

于 2013-11-02T21:48:45.300 回答
1

您可以使用以下内容,这也将排除空格并为您提供完全匹配的内容。

preg_match_all('/(?<![^ ])\d(?!\d)/', $data, $matches);

live demo

或者为了安全起见,您可以使用前瞻。

preg_match_all('/\d(?= +category)/i', $data, $matches);

live demo

更好的是,只需简单地匹配group:和以下数字。

preg_match_all('/group:\s+\K\d/i', $data, $matches);
于 2013-11-02T21:47:12.403 回答
1

您可以进行前瞻,以确保category立即执行以下操作:

preg_match_all('/:\s+\d(?= category)/', $data, $matches);

未捕获前瞻,但如果不存在,则字符串将不匹配。

于 2013-11-02T21:44:13.297 回答