首页 > 解决方案 > python中的正则表达式,需要从字符串中打印网站名称

问题描述

import re

x = 'my website name is www.algoexpert.com and i have other website too'
for line in x:
    y = line.rstrip()
z = re.findall('.*\S+/.[a-z]{0-9}/.\S+', y) 
print(z) 

我只想打印网站名称 ( www.algoexpert.com)

标签: pythonregex

解决方案


要修复的问题:

  • x本身就是一个字符串,你为什么要用它来循环它for line in x

  • [a-z]{0-9}- 尝试仅覆盖字母字符,尽管方式错误(可能是{0,9})。字符的范围应该[a-z0-9]+或至少 - [a-z]+(取决于最初的意图)

  • 点/句点.应该用反斜杠转义\.

固定版本(简化):

import re

x = 'my website name is www.algoexpert.com and i have other website too'
z = re.findall('\S+\.[a-z0-9]+\.\S+', x.strip())
print(z)   # ['www.algoexpert.com']

推荐阅读