简体   繁体   English

Java正则表达式,用于在字符串中任意位置精确地显示5位数字

[英]Java Regular Expression for number of exactly 5 digits anywhere in the string

I'm trying to create a regular expression to parse a 5 digit number out of a string no matter where it is but I can't seem to figure out how to get the beginning and end cases. 我正在尝试创建一个正则表达式来解析字符串中的5位数字,无论它在哪里,但是我似乎都无法弄清楚如何获取开头和结尾的大小写。

I've used the pattern as follows \\\\d{5} but this will grab a subset of a larger number...however when I try to do something like \\\\D\\\\d{5}\\\\D it doesn't work for the end cases. 我使用的模式如下\\\\d{5}但这会捕获更大数量的子集...但是,当我尝试做类似\\\\D\\\\d{5}\\\\D它不会不适合最终情况。 I would appreciate any help here! 在这里,我将不胜感激! Thanks! 谢谢!

For a few examples ( 55555 is what should be extracted): 举几个例子(应该提取55555 ):

At the beginning of the string
"55555blahblahblah123456677788"

In the middle of the string
"2345blahblah:55555blahblah"

At the end of the string
"1234567890blahblahblah55555"

Since you are using a language that supports them use negative lookarounds: 由于您使用的是支持它们的语言,因此请使用否定性环顾:

"(?<!\\d)\\d{5}(?!\\d)"

These will assert that your \\\\d{5} is neither preceded nor followed by a digit. 这些将断言您的\\\\d{5}既不是数字也不是数字。 Whether that is due to the edge of the string or a non-digit character does not matter. 这是由于字符串的边缘还是非数字字符无关紧要。

Note that these assertions themselves are zero-width matches. 请注意,这些断言本身就是零宽度匹配。 So those characters will not actually be included in the match. 因此,这些字符实际上不会包含在比赛中。 That is why they are called lookbehind and lookahead. 这就是为什么将它们称为后向和向前。 They just check what is there, without actually making it part of the match. 他们只是检查那里有什么,而没有真正使它成为比赛的一部分。 This is another disadvantage of using \\\\D , which would include the non-digit character in your match (or require you to use capturing groups). 这是使用\\\\D另一个缺点,它会在您的匹配项中包含非数字字符(或要求您使用捕获组)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM