1

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

4 Answers 4

3

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

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

OR

Without lookahead.

(?<=Name-)[^_]*
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

1

How would it be with

Name-(\w*?)_

If that fits your needs?

EDIT:

Name-(\w+?)_

If there must be more than one character.

Comments

0

What about this one?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.