正则表达式数字不被其他数字包围

发布于 2024-10-03 06:30:17 字数 335 浏览 1 评论 0原文

我正在尝试获取一个不被任何其他数字包围且不在数字序列中的六位数字。该数字可以存在于字符串的开头、字符串中的任何位置以及末尾。它前面还可以有逗号和文本,但最重要的是不同的 6 位数字块。我已经竭尽全力进行前瞻和条件处理,但找不到解决所有问题的完整解决方案。

样本数据:

00019123211231731ORDER NO 761616 BR ADDRESS 123 A ST
ORDER NO. 760641 JOHN DOE
REF: ORDER #761625
OP212312165 ORDER NUMBER 759699 /REC/YR 123 A ST
766911
761223,761224,761225

I'm trying to get a six digit number that is not surrounded by any other number, and is not in a sequence of numbers. This number can exist at the beginning of the string, anywhere in it, and at the end. It can also have commas and text in front of it, but most importantly distinct 6 digit blocks of numbers. I've pulled my hair out doing lookaheads and conditions and can't find a complete solution that solves all issues.

Sample data:

00019123211231731ORDER NO 761616 BR ADDRESS 123 A ST
ORDER NO. 760641 JOHN DOE
REF: ORDER #761625
OP212312165 ORDER NUMBER 759699 /REC/YR 123 A ST
766911
761223,761224,761225

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

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

发布评论

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

评论(3

愛放△進行李 2024-10-10 06:30:17

(^|\D)(\d{6})(\D|$)。您将在捕获组 2 中找到所需的 6 位匹配项。请注意,此解决方案仅对一场匹配项可靠。它不会在 123456,567890 中找到这两个数字(感谢艾伦指出这一点!)。如果需要多个匹配,则应使用环视解决方案。

使用环视:

(?<=^|\D)\d{6}(?=\D|$)

或使用环视且条件为有效数字(即第一个数字不为 0):

(?<=^|\D)[1-9]\d{5}(?= \D|$)

(^|\D)(\d{6})(\D|$). You will find your needed 6 digit match in capturing group 2. Notice that this solution is reliable only for one match. It won't find both numbers in 123456,567890 (Thank you Alan for pointing this out!). If multiple matches are needed a lookaround solution should be used.

With look-arounds:

(?<=^|\D)\d{6}(?=\D|$)

or with look-arounds and the condition to be a valid number (i.e. the first digit is not 0):

(?<=^|\D)[1-9]\d{5}(?=\D|$)

青丝拂面 2024-10-10 06:30:17

您可以使用负向后查找负向前查找来确保匹配项旁边没有数字:

(?<!\d)\d{6}(?!\d)

匹配数字,而不匹配相邻的字符。
此外,如果匹配位于字符串的开头或结尾,它也会起作用。

You can use a negative lookbehind and negative lookahead to make sure there are no digits adjacent to the match:

(?<!\d)\d{6}(?!\d)

This only matches the number, and not the adjacent characters.
Also, it works if the match is at the beginning or end of the string.

梦断已成空 2024-10-10 06:30:17

你不能轻松地使用这个正则表达式吗?

[^0-9](\d{6})[^0-9]

它应该匹配任何 6 位数字,而不是用任何其他数字填充。因此不按顺序排列。

Couldn't you just as easily use this regex

[^0-9](\d{6})[^0-9]

It should match any 6 digit number, not padded by any other numbers. Therefore not being in a sequence.

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