Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

python - Regex to extract the string

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.

question from:https://stackoverflow.com/questions/65846751/regex-to-extract-the-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) )

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...