简体   繁体   中英

How to extract a specific string in Python

I am trying to execute this curl command using python . It retrieves an output like below.

* Rebuilt URL to: <dns>
*   Trying <ip>...
* TCP_NODELAY set
* Connected to escortpersonaladz.com (<ip>) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS Unknown, Certificate Status (22):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=webdisk.escortpersonaladz.com
*  start date: May  3 02:00:53 2020 GMT
*  expire date: Aug  1 02:00:53 2020 GMT
*  subjectAltName: host "escortpersonaladz.com" matched cert's "escortpersonaladz.com"

How can I extract that particular line * expire date: Aug 1 02:00:53 2020 GMT from the above output if it is exist?

import re

curl_output = '''
* Rebuilt URL to: <dns>
*   Trying <ip>...
* TCP_NODELAY set
* Connected to escortpersonaladz.com (<ip>) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.3 (IN), TLS Unknown, Certificate Status (22):
* SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=webdisk.escortpersonaladz.com
*  start date: May  3 02:00:53 2020 GMT
*  expire date: Aug  1 02:00:53 2020 GMT
*  subjectAltName: host "escortpersonaladz.com" matched cert's "escortpersonaladz.com"
'''

match = re.search(r"(\*\s*expire date(.+?))\s*\*", curl_output)
if match:
    desired = match.group(1)
    print(desired)
    #*  expire date: Aug  1 02:00:53 2020 GMT
else:
    print("Not found")

The regex matches the string you are looking for by looking between two * s that contain the expire date . It also accounts for possible spaces before and after. If a match is found, desired string lies in the first group of the match object. In case it is not found, re.search will return None , so we check and act accordingly.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM