正则表达式在子字符串之前查找数字

Regular Expression to find number before substring

我想在 oracle 中编写一个正则表达式来查找 'M(CAT)' 或 'F(CAT)' 之前的数字。该数字可以是整数或小数。

示例:

1.   5.4M(PIG), 8F(COW), 1F(DOG), 2.9M(CAT) -- answer should be 2.9
2.   2F(PIG), 7.4M(COW), 4.6F(DOG), 3F(CAT) -- answer should be 3
3.   1.5M(CAT) -- answer should be 1.5
4.   4F(PIG), 12F(CAT) -- answer should be 12
5.   7F(COW), 2.3M(DOG) -- answer should be null
6.   7.2F(COW) -- answer should be null

注意:对于我的问题,不可能多次列出同一种动物。

Example: 5.4M(PIG), 8F(COW), 3M(COW), 1F(DOG), 2.9M(CAT), 1F(CAT) 

Regexp_substr 不支持反向引用,所以最简单的方法可能是在你的 substr 中包含 M/F(CAT),然后再删除它,例如:

rtrim(regexp_substr(str, '([0-9]+(\.[0-9])?)[MF]\(CAT\)'), 'MF(CAT)')

在此示例中,rtrim 从输出中删除任何字符 ()ACFMT

正如 mathguy 所暗示的,如果您的输入 str 为 8F(CAT), 3M(CAT),这将是 return 8(第一个匹配项)。如果您同时想要它们,最好的解决方案可能是首先 然后 运行 它们的正则表达式以提取数字。但您也可以使用 occurrence 参数更手动地提取任何第二次出现:

rtrim(regexp_substr(str, '([0-9]+(\.[0-9])?)[MF]\(CAT\)', 1, 2), 'MF(CAT)')

整个事情的一个不同选择是对 regexp_replace 使用反向引用,但我认为这更尴尬,因为您必须包含字符串的其余部分才能将其删除:

regexp_replace(str, '(^|.+ )([0-9]+(\.[0-9])?)[MF]\(CAT\).*', '')