【发布时间】:2020-10-16 22:30:33
【问题描述】:
我有一些具有这种结构的字符串:<name> (<unit>)。我想提取name和unit;为了执行这个任务,我使用regex,在大多数情况下都很好。
但是,在某些情况下,<unit> 由希腊字符组成,例如 Ω。在这些情况下,我的代码无法提取所需的两个部分。
这是我的代码:
import re
def name_unit_split(text):
name = re.split(' \([A-Za-z]*\)', text)[0]
unit = re.findall('\([A-Za-z]*\)', text)
if unit != []:
unit = unit[0][1:-1]
else:
unit = ''
return name, unit
print(name_unit_split('distance (mm)'))
我得到:
('distance', 'mm')
但是当我尝试:
print(name_unit_split('resistance (Ω)'))
我明白了:
('resistance (Ω)', '')
我搜索了其他正则表达式占位符并尝试使用这些,但没有成功:
name = re.split(' \([\p{Greek}]*\)', text)[0]
unit = re.findall('\([\p{Greek}]*\)', text)
如何使用regex在字符串中查找希腊字符(一个或多个,分组)?
此外,有没有更好的方法来使用regex 执行上述任务?我的意思是:有一种方法可以同时提取<name> 和<unit> 并将它们保存在name 和unit 和regex 中?
【问题讨论】:
标签: python regex string extract placeholder