【发布时间】:2021-03-16 13:26:36
【问题描述】:
有两个类似的字符串
'my phone number is 010-1111-1456'
'my house address is 123-456'
我的代码:
text1 = 'my phone number is 010-1111-1456'
text2 = 'my house address is 123-456'
print(re.search('[0-9]+[-]+[0-9]+[^-]', text1))
print(re.search('[0-9]+[-]+[0-9]+[^-]', text2))
输出应该是怎样的:
<re.Match object; span=(20, 27), match='123-456'>
我的输出:
<re.Match object; span=(19, 27), match='010-1111'>
<re.Match object; span=(20, 27), match='123-456'>
我的问题:我只想打印第二个像
<re.Match object; span=(20, 27), match='123-456'>
我怎样才能得到正确的代码?
【问题讨论】:
-
删除或评论这一行 print(re.search('[0-9]+[-]+[0-9]+[^-]', text1))
-
所以如果我理解正确的话,你只想匹配两批数字?将数字也添加到第二个 [^-] 中怎么样?
-
@new_be 我认为你的正则表达式是错误的。试试
print(re.search('[0-9]+[-]+[0-9]+^-', text1))或print(re.search('[0-9]+[-]+[0-9]+^[-]', text1)) -
你也可以使用这个网站来测试你的正则表达式regex101.com
标签: python python-3.x regex