正则表达式匹配模式

时间:2021-05-12 10:13:24

标签: python regex

我只想从数据中提取符号和数字

输入:<70 (aze) , <0,03 (+) , >0.03 (+)
输出:<70 , <0,03 , >0.03

尝试使用 re.sub 但我无法选择标志

re.sub("\D", "", text)

1 个答案:

答案 0 :(得分:2)

你可以使用

" , ".join(re.findall(r'[<>]?\d+(?:[.,]\d+)?', text))

参见regex demo详情

  • [<>]? - 可选的 <>
  • \d+ - 一位或多位数字
  • (?:[.,]\d+)? - ., 的可选出现,然后是一个或多个数字。

Python demo

import re
text = '<70 (aze) , <0,03 (+) , >0.03 (+)'
print( " , ".join(re.findall(r'[<>]?\d+(?:[.,]\d+)?', text)) )
# => <70 , <0,03 , >0.03

在熊猫中:

df['text'] = df['text'].str.findall(r'[<>]?\d+(?:[.,]\d+)?').str.join(' , ')