user8522293
user8522293

Reputation:

Regex in python, Need to print website name from a string

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) 

I just want to print the website name (www.algoexpert.com)

Upvotes: 2

Views: 51

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Issues to fix:

  • x is a string itself, why are you looping over it with for line in x?

  • [a-z]{0-9} - tries to cover only alphabetical chars, though in wrong way (could be {0,9}). The range of chars should be [a-z0-9]+ or at least - [a-z]+ (depending on the initial intention)

  • dots/periods . should be escaped with backslash \.

Fixed version (simplified):

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

Upvotes: 1

Related Questions