查找模式前面没有数字的正则表达式匹配

发布于 2025-01-15 17:31:13 字数 475 浏览 4 评论 0原文

我目前正在尝试从字符串中提取日期。以下是一些示例:

02.10 abcdef -> extract '02.10'
abcdef 03.12 -> extract '03.12'
abcdef 308.56 -> extract nothing

一个简单的正则表达式,例如 (\d{2}.\d{2}) 对于前两种情况工作正常,但我在第三个示例中发现了误报,即正则表达式返回 08.56,这是有道理的。

有什么办法可以防止这个字符串被提取吗?我尝试了 [^0-9](\d{2}.\d{2}) ,它似乎在正则表达式调试网站上工作,但当我将其编译为 python 正则表达式时却不起作用,

import re
regex = re.compile(r'[^0-9](\d{2}.\d{2})')

谢谢进步

I am currently trying to extract dates from strings. Here are a few examples:

02.10 abcdef -> extract '02.10'
abcdef 03.12 -> extract '03.12'
abcdef 308.56 -> extract nothing

A simple regex such as (\d{2}.\d{2}) works fine for the first two cases but I catch a false positive for the third example, the regex returns 08.56, which makes sense.

Is there any way to prevent this string from being extracted? I tried [^0-9](\d{2}.\d{2}) which seems to be working on regex debugging websites but not when I compile it as a python regex with

import re
regex = re.compile(r'[^0-9](\d{2}.\d{2})')

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不必在意 2025-01-22 17:31:13

我首先认为您需要完整的数字,可以通过以下方式实现:
(\d*\.\d{2}) 返回 308.56

但随后看到了这一行:

有什么办法可以防止该字符串被提取吗?
这让我预计你只需要两个数字,一个点,然后又是两个数字。否则正则表达式不应该返回任何内容。

那么答案应该是:

(?<![\w\d])(\d{2}\.\d{2})(?![\w\d])

您可以在 https://regex101.com/ 上测试它

输入图像描述这里

I First thought you needed the complete number which is possible with:
(\d*\.\d{2}) which returns 308.56

But then is saw the line:

Is there any way to prevent this string from being extracted?
Which made me expect you want only two numbers, a dot and again two numbers. Otherwise the regex should return nothing.

Then the answer should be:

(?<![\w\d])(\d{2}\.\d{2})(?![\w\d])

You can test it on https://regex101.com/

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文