正则表达式用于特定字符串部分后的数字

编程入门 行业动态 更新时间:2024-10-25 14:34:02
本文介绍了正则表达式用于特定字符串部分后的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

Example Input: localhost:23089/generic-url-segment-c?p=5 Expected Output : 5 Example Input: 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

更多推荐

正则表达式用于特定字符串部分后的数字

本文发布于:2023-11-03 12:57:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1555192.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   数字   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!