Anon
Anon

Reputation: 865

Extract pattern using regex

I have the following strings:

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

I need a regex in PHP that will match the following substrings in each of the above strings

AB, XYZ, JK, AB, XYZ, JK

I am currently using this the regex:

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

However in the case of

Name-AB_gate_date, Name-XYZ_gate_date and Name-JK_gate_date

It is returning

AB_gate, XYZ_gate and JK_gate

How do I get it to just match the following in these three strings?

AB, XYZ and JK

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

Upvotes: 1

Views: 52

Answers (4)

axiac
axiac

Reputation: 72206

What about this one?

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

Upvotes: 0

CptVince
CptVince

Reputation: 89

How would it be with

Name-(\w*?)_

If that fits your needs?

EDIT:

Name-(\w+?)_

If there must be more than one character.

Upvotes: 1

Aran-Fey
Aran-Fey

Reputation: 43136

All you need do is to make the (.*) non-greedy.

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

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

.* is greedy by default. Change .* in your regex to .*?. You could try this regex also,

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

OR

Without lookahead.

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

Upvotes: 3

Related Questions