获取两个字符之间的数字
我试图在如下字符串中找到两个下划线 (_) 之间的数字:
234534_45_92374
3433_9458_034857
zx_8458_047346daf
What would be the regex for this?
I am trying to find the number between two underscores (_) in strings like these:
234534_45_92374
3433_9458_034857
zx_8458_047346daf
What would be the regex for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于示例字符串的格式一致,因此您不需要包含匹配尾随下划线的验证。
使用
preg_match()
,匹配文字下划线,然后忘记匹配它(使用\K
),然后匹配一个或多个数字。匹配将是一个字符串 - 如果您需要整数类型,则将字符串转换为int
。如果您确实希望将数字转换为整数,PHP 提供了一个更直接的函数:
sscanf()
。默默地消耗一个或多个非下划线字符,然后是下划线,然后捕获一个或多个数字并使用%d
指示该值必须是int
类型变量。代码:(演示)
或
Because your sample strings appear consistently formatted, you do not need to include the validation of matching the trailing underscore.
With
preg_match()
, match the literal underscore, then forget that you matched it (using\K
), then match one or more digits. The match will be a string -- if you need an integer type, then cast the string to anint
.If you definitely want the number to be cast as an integer, PHP offers a more direct function:
sscanf()
. Silently consume the one or more non-underscore characters, then the underscore, then capture the one or more digit number and use%d
to dictate that the value must be anint
type variable.Codes: (Demo)
Or