python - 正则表达式匹配字符串中的精确模式

标签 python regex

如果我有以下字符串 '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/

相关文章:

javascript - JavaScript 正则表达式中的惰性匹配前面部分

正则表达式从带小数的文本中提取十进制数

python - 为什么我的 pylab 动画每次更新都会变慢?

python - 如何在 Snow Leopard 和其他 32 位/64 位问题上强制 Python 为 32 位

python - 在动态属性设置上绕过 mypy 的 "Module has no attribute"

mysql - 如何在mysql查询中使用正则表达式删除特定字符?

regex - 如何使用Regexp::Grammars匹配多行模式?

python - 如何根据索引位置过滤一组行?

java - 在 Java 中调用 Python?

java - 用于 OR 两个范围正则表达式的正则表达式