如何使用python在字符串分区中使用正则表达式?

2024-06-26 00:06:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,如下所示,来自熊猫数据帧列

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"

我试图获得如下所示的输出(在返回第二个连字符之前,您可以看到所有内容)

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帮助我获得预期的输出吗


Tags: 内容stringifunit字符levelpartitionsc
3条回答

使用splitjoin的简单解决方案:

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

您可以在此处使用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]

相关问题 更多 >