如何在Python中提取特定字符串

时间:2020-05-12 10:17:34

标签: python

我正在尝试使用curl执行此python命令。它检索如下的输出。

* 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"

如果存在上述特定行* expire date: Aug 1 02:00:53 2020 GMT,该如何从上面的输出中提取出来?

1 个答案:

答案 0 :(得分:0)

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

正则表达式通过在包含*的两个expire date之间进行查找来匹配您要查找的字符串。它还说明了之前和之后的可能空间。如果找到匹配项,则所需的字符串位于匹配对象的第一组中。如果找不到,re.search将返回None,因此我们进行检查并采取相应措施。