在Python中捕获句点之间的输入

2024-10-02 04:26:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我如何在没有句点的情况下捕捉句点之间的数字?在

数字最多可以是3位数,但小于3位数。0<;=1000

示例:

  • 领域。3。大黄蜂
  • 域名。56.mashabee
  • <8咖啡师

Tags: lt示例情况数字领域域名位数句点
3条回答

尝试这样做:

>>> import re
>>> text = 'domain.56.mashabee'
>>> mystr = re.compile(r'^\w+\.(\d{1,3})\.')
>>> print mystr.search(str(text)).groups()[0]
56
your_string.split(".")[1] 

会给你电话号码的

我的ipython例子外壳:-在

^{pr2}$

你的用例并不需要regex。在

当然,如果你想返回和整型,你需要做的就是转换它。在

In [49]: int(your_string.split(".")[1])
Out[49]: 3

关于正则表达式

正则表达式并不总是解决方案。有一句关于使用正则表达式的引语。在

Some people, when confronted with a problem, think
“I know, I'll use regular expressions.” Now they have two problems.

reference: http://regex.info/blog/2006-09-15/247

使用regex的可能解决方案

  1. 对正则表达式使用re模块。这是a link to the documentation。在
  2. 匹配项使用正则表达式项r"\.(\d{1,3})\."。此匹配将找到一个文本句点,后跟1、2或3个数字,然后是另一个文本句点。在
  3. 要帮助捕获数字,请使用regex捕获组(...)。在这种情况下,1、2或3位数的匹配将被捕获在括号中。这是a link to some regex examples。在

用例的示例代码

>>> 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]

相关问题 更多 >

    热门问题