Как использовать регулярное выражение в строковом разделе с помощью python?

#python #python-3.x #regex #pandas #dataframe

#python #python-3.x #регулярное выражение #панды #фрейм данных

Вопрос:

У меня есть строка, подобная показанной ниже, из столбца фрейма данных 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"
  

Я пытаюсь получить результат, подобный показанному ниже (вы можете увидеть все, прежде чем будет возвращен 2-й дефис)

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

Итак, я попробовал приведенный ниже код

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

Это означает, что я всегда хочу, чтобы все было до 2nd Hyphen ( - ).

Вместо того, чтобы вручную назначать пробелы, я хотел бы написать что-то вроде приведенного ниже. Не уверен, правильно ли приведенное ниже. можете ли вы помочь мне получить все до 2-го дефиса?

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

Может помочь мне получить ожидаемый результат с помощью partition method and regex ?

Ответ №1:

Вы могли бы использовать 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
  

Ответ №2:

Попробуйте использовать re.split вместо string.partition :

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

Ответ №3:

Простое решение с split помощью и join :

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