如何编写正则表达式来查找由句点分隔的一个或多个数字而不返回最后一个句点?
如何编写正则表达式来查找由句点分隔的一位到三位数字,而不返回最后一个句点?例如,找到字符串
1.1.
,它也需要匹配
1.1
或简单地
1
同样,它需要支持一到三位数字,因此
11.11.11
和 也
111.111.111
需要工作。
所以..字符串并不总是以句点结尾,但可能会。此外,如果它确实以句点结尾,则不要返回最后一个句点(因此,使用正向前瞻)。因此, 1.1.
如果匹配将返回 1.1
这是到目前为止我所拥有的,但我正在努力寻找一种不返回最后一个句点的方法:
(\d{1,3}\.?)+(?=(\Z|\s|\-|\;|\:|\?|\!|\.|\,|\)))
它正在返回,
6.6.
但是我想让它回来
6.6
How to write regular expression to find between one and three digits separated by periods without returning the last period? For example, find the string
1.1.
and it would also need to match
1.1
or simply
1
Likewise, it needs to support between one and three digits, so
11.11.11
and
111.111.111
need to work as well.
So..the string won't always end with a period, but it may. Further, if it does end with a period, don't return the last period (so, using a positive lookahead). So, 1.1.
if matched would return 1.1
Here is what I have so far, but I am struggling to find a way to NOT return the last period:
(\d{1,3}\.?)+(?=(\Z|\s|\-|\;|\:|\?|\!|\.|\,|\)))
It is returning
6.6.
but I want it to return
6.6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您要求:匹配dddd或dddxxx,并且无论是否以“.”结尾。无论是否,始终停在最后一个 d(而不是点)。
仅仅这样有什么问题:
(\d(\.\d)*)
如果您希望点分数字字符串由一组字符终止,请在其后面添加一个前瞻,就像您您的问题中有:
如果您还希望它匹配独立字符串(带或不带终止符),请添加 ?前瞻之后:
对于多于一位的数字,只需将 \d 替换为 \d{1,3} 等。
You require: match d.d.d.d. or d.d.dxxx, and regardless of whether it ends with a "." or not, always stop at the last d (never the dot).
What's wrong with just:
(\d(\.\d)*)
If you want your dotted-digit string to be terminated by a set of characters, put a look-ahead after it, as you have in your question:
If you also want it to match a stand-alone string (with or without the terminator), add a ? after the look-ahead:
For more than one digits, just replace \d with \d{1,3} etc.
正则表达式
(\d{1,3}(?:\.\d{1,3})*)\.{0,1}
应该可以工作。在组1中(如果将组0作为整个匹配)将存储您想要保留的字符串,不带
.
结束,以防它包含它。它基本上是这样的:
1-3
数字.d
、.dd
或.ddd
.
结束,则不会接受它,因为它不在组内。进行测试并让我们知道它是否适用于您的所有示例。
编辑:
将
+
替换为*
The regex
(\d{1,3}(?:\.\d{1,3})*)\.{0,1}
should work.In the Group 1 (if taken Group 0 as the entire match) will be stored the string you want to keep, without the
.
at the end, in case it contains it.It basically does:
1-3
digits.d
,.dd
, or.ddd
.
, it won't take it because it isn't inside the group.Do your tests and let us know if it works with all your examples.
Edit:
Replace
+
with*
快速解释:
Quick explanation:
您可以编写自己的正则表达式并在以下站点上使用虚拟数据进行测试:
http://myregexp.com/
You can write your own Regular expression and test with dummy data on following Site:
http://myregexp.com/