正则表达式用于特定字符串部分后的数字 [英] Regex for numbers after a certain string part

查看:141
本文介绍了正则表达式用于特定字符串部分后的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式提取网址中的数字。

I'm trying to extract numbers inside an URL with regex.

Example Input: http://localhost:23089/generic-url-segment-c?p=5

Expected Output : 5

Example Input: http://localhost:23089/generic-url-segment-c?p=12&sort=5

Expected Output: 12

首先,我尝试查找混合了 string.replace , string.indexof substring ,但认为Regex会更容易。

First I tried to look for the numbers with a mixture of string.replace,string.indexof and substring but thought Regex would be easier.

到目前为止,我尝试使用((p =)?=。),但不能只获得5个

So far I tried using ((p=)?=.) but can't get the 5 only.

同样如第二个示例所示,该值可能是两位数,甚至后面可能还有其他参数。因此,也许有必要在 p = & 之间进行搜索,但我不知道Regex在缺少以下内容时的行为参数。

And also as shown in second example, this value might be a two digit value or there even might be other parameters after it. So maybe a search between p= and & is necessary but I don't know how Regex behaves in absence of parameters.

推荐答案

尝试以下模式。加号匹配1个或多个,因此您可以获得1个或多个数字-

Try the below pattern. The plus matches 1 or more so you can get 1 or more digits -

 p=(\d+)

方括号是一个组,因此使用

The brackets are a group so to get the value of the match within the group use

match.Groups[1].Value

这篇关于正则表达式用于特定字符串部分后的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆