matchResult=re.findall(r'(\d{3,4})-(\d{7,8})',text)
时间: 2024-02-06 14:13:12 浏览: 106
这行代码的作用是使用正则表达式在文本中查找匹配的电话号码,每个电话号码的格式为三到四个数字,接着一个短横线“-”,再接着七到八个数字。这个正则表达式中使用了两个捕获组,分别用于捕获区号和号码。`re.findall()` 方法会返回所有符合条件的匹配结果,以列表形式存储在 `matchResult` 变量中。
相关问题
import re text='''Suppose my Phone No.is 0535-1234567, yours is 010-12345678, his is 025-87654321.''' matchResult=re.findall(r'(\d{3,4})-(\d{7,8})',text) #注意大括号内逗号后不能有空格 for item in matchResult: print(item[0],item[1],sep='-')
以上代码的输出结果是:
```
0535-1234567
010-12345678
025-87654321
```
程序中两处有错误,请给出错误行的编号、错误的原因和改正后的整行代码。 import re telNumber = '''Suppose my Phone No. is 0535-1234567, yours is 010-12345678, his is 025-87654321.''' pattern = re.compile(r'(\d)-(\d{7,8})') index = 0 while True: matchResult = pattern.findall(telNumber, index) if not matchResult: break print('-'*30) print('Success:') for i in range(3): print('Searched content:', matchResult.group(i),\ ' Start from:', matchResult.start(i), 'End at:', matchResult.end(i),\ ' Its span is:', matchResult.span(i)) index = matchResult.end(2)
错误行的编号是第9行。原因是在print语句中使用了反斜杠续行,但是没有加上引号。应该修改为:
```python
print('Searched content:', matchResult.group(i), ' Start from:', matchResult.start(i), 'End at:', matchResult.end(i), ' Its span is:', matchResult.span(i))
```
另外,第7行应该将pattern.findall()的参数改为telNumber[index:],表示从telNumber的第index个字符开始查找。修改后的代码如下:
```python
import re
telNumber = '''Suppose my Phone No. is 0535-1234567, yours is 010-12345678, his is 025-87654321.'''
pattern = re.compile(r'(\d)-(\d{7,8})')
index = 0
while True:
matchResult = pattern.findall(telNumber[index:])
if not matchResult:
break
print('-'*30)
print('Success:')
for i in range(3):
print('Searched content:', matchResult[i][0]+'-'+matchResult[i][1], ' Start from:', matchResult[i].start(), 'End at:', matchResult[i].end(), ' Its span is:', (matchResult[i].start()+index, matchResult[i].end()+index))
index += matchResult[-1].end()
```
改正后的代码在输出结果方面也做了一些修改,使其符合预期。
阅读全文
相关推荐
















