簡體   English   中英

如何使用 python 在字符串分區中使用正則表達式?

[英]How to use regex in string partition using python?

我有一個如下所示的字符串,來自 pandas 數據框列

string = "insulin MixTARD  30/70 -  inJECTable 20 unit(s)  SC (SubCutaneous)     -   Hypoglycaemia Protocol if Blood Glucose Level (mmol)  <  4     -   Call Doctor if Blood Glucose Level (mmol)  >  22"

我正在嘗試獲取如下所示的 output(您可以在返回第二個連字符之前看到所有內容)

insulin MixTARD  30/70 -  inJECTable 20 unit(s)  SC (SubCutaneous)

所以,我嘗試了下面的代碼

string.partition('   -')[0]  # though this produces the output, not reliable

意思是,我總是想要第二個Hyphen ( - ) 之前的所有內容。

我不想手動分配空格,而是想寫如下內容。 不確定以下是否正確。 你能幫我得到第二個連字符之前的所有東西嗎?

string.partition(r'\s{2,6}-')[0]

可以幫助我使用partition method and regex獲得預期的 output 嗎?

您可以在此處使用re.sub作為單行解決方案:

string = "insulin MixTARD  30/70 -  inJECTable 20 unit(s)  SC (SubCutaneous)     -   Hypoglycaemia Protocol if Blood Glucose Level (mmol)  <  4     -   Call Doctor if Blood Glucose Level (mmol)  >  22"
output = re.sub(r'^([^-]+?-[^-]+?)(?=\s*-).*$', '\\1', string)
print(output)

這打印:

insulin MixTARD  30/70 -  inJECTable 20 unit(s)  SC (SubCutaneous)

正則解釋:

^               from the start of the input
    (           capture
        [^-]+?  all content up to
        -       the first hyphen
        [^-]+?  all content up, but not including
    )           end capture
    (?=\s*-)    zero or more whitespace characters followed by the second hyphen
    .*          then match the remainder of the input
$               end of the input

嘗試使用re.split而不是string.partition

re.split(r'\s{2,6}-', string)[0]

使用splitjoin的簡單解決方案:

"-".join(string.split("-")[0:2])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM