Stephanie Safflower
Stephanie Safflower

Reputation: 177

Regex to match any number after certain strings

I want to match the userid number in a url string that's usually after a id= or /user/

Examples:

http://dummy.url/url/path/id=7623
http://dummy.url/url/path/user/8743
http://dummy.url/url/path/user/56
http://dummy.url/url/path=88772/user/890&more=87273&variables&here=76233
http://dummy.url/url/path/id=2818372

I need to match 7623, 8743, 56, 890, 2818372

I haven't tried much on this as I'm a complete noob at regex and I only know how to mach numbers, all numbers, so if the url has any it will match them as well

The numbers will always be positive integers

Upvotes: 1

Views: 11433

Answers (1)

revo
revo

Reputation: 48711

You can do it by defining an alternation:

(?:user\/|id=)\K\d+

Live demo

Explanation:

(?:         # Start of a non-capturing group
    user\/      # Match `user/`
    |           # Or
    id=         # `id=`
)           # End of non-capturing group
\K\d+       # Forget matched strings then match digits

Javascript way:

var url = "http://dummy.url/url/path/user/56";
console.log(url.replace(/(user\/|id=)\d+/, function(match, p1) {
	return p1 + 'id';
}));

Upvotes: 5

Related Questions