0

我需要在具有以下格式混合结构的字符串中获取较低和较高的值:

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)

我在上面的示例中添加了更多示例(尤其是小于)。如果文本中有“小于”,我想编写获取值的正则表达式。

以下给了我不需要的“无”。

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

1 回答 1

2

IMO,您不会仅使用正则表达式获得可靠的解决方案。如果是我,我会把它分解成多个条件和正则表达式。话虽如此,对于狗屎和笑容,我确实想出了这个......它确实匹配上面的所有内容,但它很丑; 对于初学者,数据根据格式被捕获到不同的组......

(?(?=.*:).*:\s*([0-9.]+)\s*-\s*([0-9.]+)|(?(?=.*\<=)(.*?)<=\s*([0-9.]+)\s*(.*)|([0-9.]+)\s*-\s*([0-9.]+)\s*(.*)))
于 2013-01-28T15:31:01.073 回答