如果我有以下字符串 'some numbers 66666666666666666667867866 and serial 151283917503423 and 8888888' 并且我想找到 15 位数的数字(所以只有 151283917503423)我该怎么做才能使它不匹配更大的数字并处理字符串可能只是 '151283917503423' 因此我无法通过它可能在两边都包含空格来识别它?
serial = re.compile('[0-9]{15}')
serial.findall('some numbers 66666666666666666667867866 and serial 151283917503423 and 8888888')
这会返回 66666666666666666667867866 和 151283917503423 但我只想要后者
最佳答案
使用word boundaries :
serial = re.compile(r'\b[0-9]{15}\b')
\b Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of alphanumeric or underscore characters, so the end of a word is indicated by whitespace or a non-alphanumeric, non-underscore character. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string, so the precise set of characters deemed to be alphanumeric depends on the values of the UNICODE and LOCALE flags. For example, r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'. Inside a character range, \b represents the backspace character, for compatibility with Python’s string literals.
关于python - 正则表达式匹配字符串中的精确模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34425219/