如何在没有句点的情况下捕获句点之间的数字?
这些数字最多可以是 3 位数,但小于 3 位数。0 <= 我 < 1000
例子:
- 领域。3.大黄蜂
- 领域。56.玛莎比
- 领域。第898章
your_string.split(".")[1]
会给你号码
我的 ipython shell 中的示例:-
In [47]: your_string = "domain.3.bumblebee"
In [48]: your_string.split(".")[1]
Out[48]: '3'
您的用例并不需要正则表达式。
当然,如果你想返回整数,你需要做的就是强制转换它。
In [49]: int(your_string.split(".")[1])
Out[49]: 3
正则表达式并不总是解决方案。有一个关于使用正则表达式的引用。
有些人在遇到问题时会想
“我知道,我会使用正则表达式”。现在他们有两个问题。
regex
re
模块进行正则表达式。这是文档的链接。r"\.(\d{1,3})\."
. 此匹配将找到一个文字句点,后跟一个 1、2 或 3 位数字,然后是另一个文字句点。(...)
。在这种情况下,括号中捕获了 1、2 或 3 位数字的匹配。这是一些正则表达式示例的链接。>>> import re
>>>
>>> subject = """
... domain.3.bumblebee
... domain.56.mashabee
... domain.898.barista
... """
>>>
>>> matches = re.finditer(r"\.(\d{1,3})\.",subject)
>>> results = [int(match.group(1)) for match in matches]
>>>
>>> results
[3, 56, 898]
尝试这样做:
>>> import re
>>> text = 'domain.56.mashabee'
>>> mystr = re.compile(r'^\w+\.(\d{1,3})\.')
>>> print mystr.search(str(text)).groups()[0]
56