请求优化正则表达式以拆分关联的企业名称、电话、城镇及邮箱
Fixing the Regex to Split Company, Town, Phone, and Email
Looks like your original regex had a few key issues: it was incomplete, anchored to the start of the string (so it only matched the first entry), and didn’t properly separate the company name from the town. Let’s fix this by using a regex that captures each component of every entry cleanly.
Corrected Code
import re a = """ ABC Limited, Nairobi0754009522info@kenyagreats.com DEF Limited, Nairobi0737 308 793info@defoptions.co.ke GHI Electrical Services, Mombasa+254787254230info@ghielectricalservices.co.ke JKL Limited, Kakamega+254541112470jkl@yahoo.com MNO Kenya, Nairobi0797429578mnoe@gmail.com""" # Clean up leading/trailing whitespace from the input string cleaned_text = a.strip() # Regex pattern to capture company name, town, phone number, and email for each entry entry_pattern = r'([A-Za-z ]+), ([A-Za-z]+)([\+\d ]+)([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})' # Extract all entries using the pattern entries = re.findall(entry_pattern, cleaned_text) # Print the results in a readable format for index, (company, town, phone, email) in enumerate(entries, 1): print(f"Entry {index}:") print(f" Company: {company.strip()}") print(f" Town: {town}") print(f" Phone: {phone.strip()}") print(f" Email: {email}") print()
Breakdown of the Regex
Let’s unpack what each part of entry_pattern does:
([A-Za-z ]+): Captures the company name (supports letters and spaces, e.g., "GHI Electrical Services"),: Matches the comma and space separating the company from the town([A-Za-z]+): Captures the town (only letters, e.g., "Mombasa" or "Kakamega")([\+\d ]+): Captures the phone number (handles+symbols, digits, and spaces, e.g., "+254787254230" or "0737 308 793")([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}): Uses a standard email regex snippet to capture valid email addresses, including domains with multiple dots.
Sample Output
When you run the code, you’ll get this structured output:
Entry 1: Company: ABC Limited Town: Nairobi Phone: 0754009522 Email: info@kenyagreats.com Entry 2: Company: DEF Limited Town: Nairobi Phone: 0737 308 793 Email: info@defoptions.co.ke Entry 3: Company: GHI Electrical Services Town: Mombasa Phone: +254787254230 Email: info@ghielectricalservices.co.ke Entry 4: Company: JKL Limited Town: Kakamega Phone: +254541112470 Email: jkl@yahoo.com Entry 5: Company: MNO Kenya Town: Nairobi Phone: 0797429578 Email: mnoe@gmail.com
Why the Original Code Failed
- Your regex was incomplete (missing closing brackets and parentheses)
- The
^anchor restricted matches to only the start of the string, not all entries - It didn’t split the company name and town into separate capture groups
- The email capture group was improperly defined and missing critical characters
内容的提问来源于stack exchange,提问作者Harrod Domer
相关产品推荐
相关产品推荐

