簡體   English   中英

SQL中的正則表達式-需要提取多行字符串的最后三個部分

[英]Regular Expression in SQL - Need to extract the last three sections of a multiline string

我對此很費時間。我需要創建一個SQL查詢,該查詢返回一個自定義字段,該字段由多行字符串的最后三個部分組成(CLOB字段)。 該數據庫是Oracle。 我選擇使用REGEXP_SUBSTR函數來嘗試使此工作。 即使使用C#或Java解析起來很容易,但我僅限於SQL,因此無法使用代碼來實現。

這是原始字段中數據的示例:

2000-01-01: Description section containing any valid text characters, including
    other dates(not followed by a colon), and potentially other hyphenated
    characters.  Potentially has multiple newline characters.
-
2001-01-01: 2nd section with different content, but following same parameters
    as first section.
-
2002-01-01: 3rd section with different content, but following same parameters
    as first section.
-
2003-01-01: 4th section with different content, but following same parameters
    as first section.
-
2004-05-05: 5th section with different content, but following same parameters
    as first section.

因此,基於以上數據,我想獲取最后三個部分,如下所示:

2002-01-01: 3rd section with different content, but following same parameters
    as first section.
-
2003-01-01: 4th section with different content, but following same parameters
    as first section.
-
2004-05-05: 5th section with different content, but following same parameters
    as first section.

我已經嘗試了許多RegEx表達式,並且能夠匹配字符串的前幾個部分,但是在不無意中匹配整個字符串的情況下,找不到一種將其限制為最后三個部分的方法。

這是我最近的嘗試:

SELECT REGEXP_SUBSTR(CLOB_FIELD_1, '(<date>.*?-\s+){0,2}(<date>.*?$)', 1, 1, 'n')
FROM MY_TABLE

為了便於閱讀,我用<date>替換了日期匹配的正則表達式部分。 無論您在何處看到<date> ,實際的正則表達式都將包含以下內容:

(19|2\d)?\d\d([-/.])(0?[1-9]|1[012])\2(0?[1-9]|[12]\d|3[01]):

基本上,這是匹配日期格式YYYY-MM-DD:YYYY/MM/DD:YYYY.MM.DD:限制性很強的方法。

使用此表達式將返回整個字符串,因為結尾處是.*?$ 我很確定? 是不必要的,但這是我使它不貪心的嘗試。

我到過我最喜歡的RegEx參考站點 ,但是找不到任何有效的方法。 我花了很多時間研究前瞻性分組和后向分組,但找不到使它起作用的方法。

如果有人能想到實現此目標的方法,無論是否熟練,我都會非常感激。 我在想應該有一種更簡單的方法來完成此操作,但是我還是看不到它。 有什么想法嗎???

不了解Oracle,但是我認為這會起作用:

  1. 首先,對整個字符串使用REVERSE函數。
  2. 在反向字符串((\\n|.)*?(<reversedDate>)){3}上使用以下正則表達式。 顯然,我要為您確定相反的日期。 或者(不確定在Oracle中的外觀),只需將其復制三遍。
  3. 再次使用REVERSE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM