使用正则表达式提取模式

时间:2014-12-29 14:17:41

标签: php regex

我有以下字符串:

Name-AB_date, Name-XYZ_date, Name-JK_date, Name-AB_gate_date, Name-XYZ_gate_date, Name-JK_gate_date

我需要PHP中的正则表达式,它将匹配上述每个字符串中的以下子字符串

AB, XYZ, JK, AB, XYZ, JK

我目前正在使用regex

(?<=Name-)(.*)(?=_)

但是在

的情况下
Name-AB_gate_date, Name-XYZ_gate_date and Name-JK_gate_date

它正在返回

AB_gate, XYZ_gate and JK_gate

如何让它与这三个字符串中的以下内容匹配?

AB,XYZ和JK

Permlink:http://www.phpliveregex.com/p/96Y

4 个答案:

答案 0 :(得分:3)

默认情况下,

.*贪婪。将正则表达式中的.*更改为.*?。你也可以试试这个正则表达式,

(?<=Name-)[^_]*(?=_)

OR

没有前瞻。

(?<=Name-)[^_]*

答案 1 :(得分:1)

您需要做的就是让(.*)非贪婪。

(?<=Name-)(.*?)(?=_)

答案 2 :(得分:1)

如何使用

Name-(\w*?)_

如果符合您的需求?

编辑:

Name-(\w+?)_

如果必须有多个角色。

答案 3 :(得分:0)

这个怎么样?

Name-([^_]*)_.*