Regex to match any number after certain strings

倾然丶 夕夏残阳落幕 提交于 2021-02-20 04:28:05

问题


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


回答1:


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';
}));


来源:https://stackoverflow.com/questions/42890978/regex-to-match-any-number-after-certain-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!