Python中的正则表达式和范围结构

2024-06-25 06:22:09 发布

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

我需要在具有以下格式混合结构的字符串中获取上下限值:

Rules:
1. If lower and upper range is available then they are separated by '-'. 
2. Sometimes the range is written as <=xx.y

2a. If 'less than' is anywhere in the text then search for the number. pl. see Example below:

3. If at all age range appears then it appears always before the range, separated from range by a ':'
4. the unit is optional

示例数据

10.0 - 35.0 MCG/ML
<=6.0 MG/24 H
51-60 YEARS: 37-129
15 - 60
0.5-9.9 %
LESS THAN 30 PG/ML
LESS THAN OR EQUAL 35 UG/DL
LESS THAN OR EQUAL TO 35
NEGATIVE: LESS THAN 20
REF RANGE LESS THAN 2.0
1.3 OR LESS PMOL/L
LAR: LESS THAN 1 NG/M

根据上面的示例,我的输出是:

10.0,35.0, MCG/ML
0, 6.0, MG/24 H
37, 129,
15,60
0.5, 9.9, %

编辑:

the string is in 'refVal'
re.search(r'([0-9]*\.?[0-9]*)\s*-\s*([0-9]*\.?[0-9]*)', refVal)
re.search(r'(<=|<|<\s*=|<\sOR\s=)\s*([0-9.]+)', refVal)

我在上面的例子中添加了更多的例子(尤其是对于小于。 如果文本中有'Less Than',我想编写正则表达式来获取值。你知道吗

下面给出了我不想要的“无”。你知道吗

>>> re.search(r'([0-9.]+) OR LESS|LESS THAN ([0-9.]+)', '5.4 OR LESS').groups()
('5.4', None)

Tags: ortheinresearchbyifis
1条回答
网友
1楼 · 发布于 2024-06-25 06:22:09

在我看来,仅仅使用regex是无法得到可靠的解决方案的。如果是我,我会把它分解成多个条件和正则表达式。话虽如此,对于大便和露齿而笑,我确实想到了这个…它确实匹配上述所有内容,但它相当难看;对于初学者来说,根据格式不同,数据被捕获到不同的组中。。。你知道吗

(?(?=.*:).*:\s*([0-9.]+)\s*-\s*([0-9.]+)|(?(?=.*\<=)(.*?)<=\s*([0-9.]+)\s*(.*)|([0-9.]+)\s*-\s*([0-9.]+)\s*(.*)))

相关问题 更多 >