Oracle:REGEXP_SUBSTR来提取所需的字符串

时间:2013-09-05 05:16:59

标签: sql oracle

我在列中有一个MID: 124281-2 - SID: 31701的字符串格式。

需要从中提取124281-231701

尝试了

SELECT REGEXP_SUBSTR('MID: 124281-2 - SID: 31701', ':[^,]+-') FROM DUAL;

但结果是: 124281-2 -

如何删除:-

提前致谢

2 个答案:

答案 0 :(得分:0)

  

有些人在遇到问题时会想“我知道,我会用   正则表达式。“现在他们有两个问题。 - Jamie Zawinski

这并不是说永远不要使用正则表达式,但在这种情况下,可能有一个更简单的选择;你能尝试使用更简单的方法 - 例如,SUBSTR字符6到13(124281-2)和字符22到26(31701)?这是假设固定的子串长度,你可能没有 - 但值得一看。

或者,如果必须使用正则表达式,则需要使用组来捕获所需的两个值;尝试更具体 - 类似[A-Z]+: ([0-9\-]+) \- [A-Z]+: ([0-9]+)

答案 1 :(得分:0)

来自:

  

' MID:124281-2 - SID:31701'

只获得124281-2的正则表达式是:

[0-9]{1,6}-[0-9]

描述:

[0-9]{1,6} match a single character present in the list below
    Quantifier: Between 1 and 6 times, as many times as possible, giving back as
                needed.
    0-9 a single character in the range between 0 and 9
- matches the character - literally
[0-9] match a single character present in the list below

如果所需字符的限制在':'之间。和' - '您可以使用以下正则表达式:

(?<=:\s)[^,]+(?=\s-)

描述:

    (?<=:\s) Positive Lookbehind - Assert that the regex below can be matched
        : matches the character : literally
        \s match any white space character [\r\n\t\f ]
    [^,]+ match a single character not present in the list below
        Quantifier: Between one and unlimited times, as many times as possible,
                    giving back as needed.
        , the literal character ,
    (?=\s-) Positive Lookahead - Assert that the regex below can be matched
        \s match any white space character [\r\n\t\f ]
        - matches the character - literally

希望这会有所帮助。