I have a hostname like
ab-test-db-dev.0002-colo1-vm234.abc.domain.com
(yeah there is no convention followed internally for hostname.)
I was trying to split this hostname to
ab-test-db-dev.0002-colo1-vm234
pattern is to split with the '.', but only if there are no other special characters following that dot.
I tried
pattern = domain.split(".")
but it is taking only till
ab-test-db-dev and not ab-test-db-dev.0002-colo1-vm234
as the first element.
What is the best way to achieve this?
You could remove the first part until no more dashes remain; that'd be the domain name to remove from the hostname:
hostname = domain
while '-' in domain:
domain = domain.partition('.')[-1]
hostname = hostname[:-len(domain) - 1]
or the other way around, remove the last part if it doesn't contain dashes, with str.rpartition()
:
hostname = domain
while True:
first, _, end = hostname.rpartition('.')
if '-' in end:
break
hostname = first
Using a regular expression looking for any part that only contains letters and dots:
import re
hostname = re.sub(r'\.[a-z.]+$', '', domain)
Demo:
>>> domain = 'ab-test-db-dev.0002-colo1-vm234.abc.domain.com'
>>> hostname = domain
>>> while '-' in domain:
... domain = domain.partition('.')[-1]
...
>>> hostname[:-len(domain) - 1]
'ab-test-db-dev.0002-colo1-vm234'
>>> domain = 'ab-test-db-dev.0002-colo1-vm234.abc.domain.com'
>>> hostname = domain
>>> while True:
... first, _, end = hostname.rpartition('.')
... if '-' in end:
... break
... hostname = first
...
>>> hostname
'ab-test-db-dev.0002-colo1-vm234'
>>> import re
>>> re.sub(r'\.[a-z.]+$', '', domain)
'ab-test-db-dev.0002-colo1-vm234'
Didn't get the pattern but for this case the following can work.
(?<=\d)\.
Try this:
https://regex101.com/r/rU8yP6/21
Use re.split
.
import re
re.split(r"(?<=\d)\.",test_Str)
Or
^(.*?)(?!.*-)\.
Try this:
https://regex101.com/r/rU8yP6/22
import re
print re.findall(r"^(.*?)(?!.*-)\.",test_str)
If I understood your question correctly, then this regex should do the job:
.*?(?=\\.(?!.*[^\\w.]))
>>> print re.match(r'.*?(?=\.(?!.*[^\w.]))', 'ab-test-db-dev.0002-colo1-vm234.abc.domain.com')
ab-test-db-dev.0002-colo1-vm234
Explanation:
.*? # match everything up to...
(?=
\. # the first dot...
(?! # that isn't followed by...
.* # any text and...
[^\w.] # something that's not a word character or a dot.
)
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.