Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to extract the string

Tags:

python

regex

I need help with regex to get the following out of the string

dal001.caxxxxx.test.com. ---> caxxxxx.test.com
caxxxx.test.com -----> caxxxx.test.com

So basically in the first example, I don't want dal001 or anything that starts with 3 letters and 3 digits and want the rest of the string if it starts with only ca.

In second example I want the whole string that starts only with ca.

So far I have tried (^[a-z]{3}[\d]+\.)?(ca.*) but it doesn't work when the string is dal001.mycaxxxx.test.com.

Any help would be appreciated.

like image 224
developthou Avatar asked Aug 09 '26 06:08

developthou


1 Answers

You can use

^(?:[a-z]{3}\d{3}\.)?(ca.*)

See the regex demo. To make it case insensitive, compile with re.I (re.search(rx, s, re.I), see below).

Details:

  • ^ - start of string
  • (?:[a-z]{3}\d{3}\.)? - an optional sequence of 3 letters and then 3 digits and a .
  • (ca.*) - Group 1: ca and the rest of the string.

See the Python demo:

import re
rx = r"^(?:[a-z]{3}\d{3}\.)?(ca.*)"
strs = ["dal001.caxxxxx.test.com","caxxxx.test.com"]
for s in strs:
  m = re.search(rx, s)
  if m:
    print( m.group(1) )
like image 131
Wiktor Stribiżew Avatar answered Aug 10 '26 19:08

Wiktor Stribiżew



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!