Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression in Python

Tags:

python

regex

I'm trying to build a list of domain names from an Enom API call. I get back a lot of information and need to locate the domain name related lines, and then join them together.

The string that comes back from Enom looks somewhat like this:

SLD1=domain1
TLD1=com
SLD2=domain2
TLD2=org
TLDOverride=1
SLD3=domain3
TLD4=co.uk
SLD5=domain4
TLD5=net
TLDOverride=1

I'd like to build a list from that which looks like this:

[domain1.com, domain2.org, domain3.co.uk, domain4.net]

To find the different domain name components I've tried the following (where "enom" is the string above) but have only been able to get the SLD and TLD matches.

re.findall("^.*(SLD|TLD).*$", enom, re.M) 
like image 278
Will Jennings Avatar asked Jul 23 '26 06:07

Will Jennings


1 Answers

Edit: Every time I see a question asking for regular expression solution I have this bizarre urge to try and solve it without regular expressions. Most of the times it's more efficient than the use of regex, I encourage the OP to test which of the solutions is most efficient.

Here is the naive approach:

a = """SLD1=domain1
TLD1=com
SLD2=domain2
TLD2=org
TLDOverride=1
SLD3=domain3
TLD4=co.uk
SLD5=domain4
TLD5=net
TLDOverride=1"""

b = a.split("\n")
c = [x.split("=")[1] for x in b if x != 'TLDOverride=1']
for x in range(0,len(c),2):
    print ".".join(c[x:x+2])

>> domain1.com
>> domain2.org
>> domain3.co.uk
>> domain4.net
like image 78
zenpoy Avatar answered Jul 25 '26 21:07

zenpoy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!