John Lee
John Lee

Reputation: 45

Using re.findall to match a string in html

I want to use re.findall() to match instances of business names from a review website. For example, I'd like to capture names in a list like the ones in the example below:

website_html = ', Jimmy Bob's Tune & Lube, Allen's Bar & Grill, Joanne's - Restaurant,'
name_list = re.findall('[,]\s*([\w\'&]*\s?)*[,]', website_html)

My code isn't catching any patterns. Any ideas?

Upvotes: 1

Views: 845

Answers (1)

Life is complex
Life is complex

Reputation: 15619

You only provided one input example, so this answer is based on your question as is:

# I replace the single quotes at the start and end of your input, because 
# Bob's throws a SyntaxError: invalid syntax
# 
website_html = ", Jimmy Bob's Tune & Lube,"

# I removed re.findall, because you only had one example so re.search or 
# re.match works.  
name_list = re.search(r'[,]\s*([\w\'&]*\s?)*[,]', website_html)

print (name_list.group(0))
# output
, Jimmy Bob's Tune & Lube,

If you have additional input values in website_html please provide them, so that I can modified my answer.

Here is the version that uses re.findall.

# I replace the single quotes at the start and end of your input, because 
# Bob's throws a SyntaxError: invalid syntax
# 
website_html = ", Jimmy Bob's Tune & Lube,"

# I wrapped your pattern as a capture group
name_list = re.findall(r'([,]\s*([\w\'&]*\s?)*[,])', website_html)

print (type(name_list))
# output 
<class 'list'>

print (name_list)
# output 
[(", Jimmy Bob's Tune & Lube,", '')]

UPDATED ANSWER

This answer is based on the modified input to your original question.

website_html = ", Jimmy Bob's Tune & Lube, Allen's Bar & Grill, Joanne's - Restaurant,"
name_list = re.findall(r'[?:,].*[?:,]', website_html)
for item in name_list:
  split_strings = (str(item).split(','))
  for string in split_strings:
     print (string)

     # output 
     Jimmy Bob's Tune & Lube
     Allen's Bar & Grill
     Joanne's - Restaurant

Upvotes: 1

Related Questions