1

I am new in Stackoverflow and I have a simple question: I need to create a regex to match a custom patterns in string. I want to create a regex to detect this url:

/post-title-92581_1.html

where $match[0] = 92581 and $match[1] = 1

I created this regex ((\-[0-9]+)_([1-2]{1}).html) works fine,but this returns:

$match[0] // -92581
$match[1] // 1

if i change string to /post-title-925-81_1.html i get

$match[0] // -81
$match[1] // 1

I only want to get the FIRST MATCH (-925) without "-".

2 Answers 2

1

One solution would be to split the RegEx:

A first regex that searches for "925" (-(\d+)[-_]),

A second regex that searches for the last part (_([1-2]{1}).html$).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, I appreciate it,now I understand better Regular Expressions,it worked for me,thanks!.
0

Put the - outside of the brackets...

-([0-9]+)_([1-2]{1}).html

Everything inside the brackets gets returned as a match!

2 Comments

This working worderful, exactly that I needed,thanks.
This gives you 81 on the second case though, while I thought you wanted 925.

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.