如何告诉正则表达式从特定位置开始并以字符串中的另一个特定位置结束? [英] How to tell regex that start from a specifc position and end in another specifc position in a string ?

查看:395
本文介绍了如何告诉正则表达式从特定位置开始并以字符串中的另一个特定位置结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我有一个像这样的字符串。

这是一个带有215 [145]的示例字符串 - Microsoft Word

有时候,有可能有这样的字符串。

这是一个带有85的示例字符串 - Microsoft Word



在这两种情况下,我想提取数字。确切地说,我希望第一个字符串为215,第二个字符串为85。

所以我计划使用正则表达式。这是我的伪正则表达式 -

字符串的左边必须是一个空格,然后只捕获至少一个数字到最多3个数字的数字,然后结束位置必须是空格或[符号。

如何告诉正则表达式获取我的字符串?



我尝试了什么:



Hi all,
I have a string like this.
"This is a sample string with 215[145] - Microsoft Word"
And sometimes, there is possibility to have a string like this.
"This is a sample string with 85 - Microsoft Word"

In both cases, i want to extract the numbers. To be precise , i want "215" from first string and "85" from second string.
So i planned to use regex. This is my pseudo regex -
"Left side of the string must be a space, Then only catch numbers atleast one digit to maximum 3 digts, Then end position must be a space or a "[" sign.
How to tell regex to get my string ?

What I have tried:

"\s[0-9]{1,3}[^[\s]]"

推荐答案

尝试:

Try:
(?<=^[^\d]*)\d+(?=[^\d]*.*




它将第一个数字之外的任何内容视为排除前缀,匹配所有连续数字,然后将该行的其余部分视为排除后缀。


It treats anything up to the first digit as an excluded prefix, matches all contiguous digits, then treats the rest of the line as an excluded suffix.


不是解决方案,只需几个链接即可帮助您理解/构建/调试RegEx。

以下是RegEx文档的链接:

perlre - perldoc.perl.org [ ^ ]

这是链接到帮助构建RegEx并调试它们的工具:

.NET正则表达式测试程序 - 正则表达式风暴 [ ^ ]

Expresso正则表达式工具 [ ^ ]

这个显示RegEx是一个很好的图表,它非常有助于理解RegEx的作用:

Debuggex:在线视觉正则表达式测试程序。 JavaScript,Python和PCRE。 [ ^ ]
Not a solution, just a few links ti help you to understand/build/debug RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]


这篇关于如何告诉正则表达式从特定位置开始并以字符串中的另一个特定位置结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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