Skip to content
Advertisement

Regex to get part of the string after dot and before hyphen?

I’m new to regex and have tried to get the regex expression in Python for the following string but still no luck. Just wondering if anyone know the best regex to get group1 from:

test-50.group1-random01.ab.cd.website.com

Basically, I was trying to get the part of string after the first dot and before the second hyphen

Advertisement

Answer

You can just do it with str.split

s = "test-50.group1-random01.ab.cd.website.com"
after_first_dot = s.split(".", maxsplit=1)[1]
before_hyphen   = after_first_dot.split("-")[0]
print(before_hyphen)  # group1

With a regex, take what is between dot and hyphen

result = re.search(r".(.*?)-", s).group(1)
print(result)  # group1
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement