字符串中的最后一个字符匹配

时间:2018-05-17 08:03:37

标签: sql oracle oracle11g

我的要求是将下面的字符与表格列中的值匹配。这些字符应该是字符串中的值。

字符:

JR
SR
II
III

表列值可以是:

'MANFORTI JR','KRUMPAK III','PURDY II','MARRONE SR'

如果字符与列值匹配,则只需获取 字符值并将其视为名称的后缀。

问题: 尝试匹配II时会出现问题。正在获取该值 其中列值在字符串中有III。(请参阅附件截图)

你能否建议如何进行完全匹配?

我想出了以下查询以匹配字符串..

SELECT LAST_NAME A,
        CASE    WHEN REGEXP_INSTR(LAST_NAME, 'JR$') > 0
                THEN SUBSTR(LAST_NAME,REGEXP_INSTR(LAST_NAME, 'JR$'), LENGTH(LAST_NAME))
                WHEN REGEXP_INSTR(LAST_NAME, 'SR$') > 0
                THEN SUBSTR(LAST_NAME,REGEXP_INSTR(LAST_NAME, 'SR$'), LENGTH(LAST_NAME))       
                WHEN REGEXP_INSTR(LAST_NAME, 'II$') > 0  
                THEN SUBSTR(LAST_NAME,REGEXP_INSTR(LAST_NAME, '[II]$'), LENGTH(LAST_NAME))

        END SUFFIX
        FROM TBL_LAST_NAME
        WHERE LAST_NAME IN ('MANFORTI JR','KRUMPAK III','PURDY II','MARRONE SR')

输出

enter image description here

1 个答案:

答案 0 :(得分:2)

在后缀之前添加一个空格(您也可以使用LIKE而不是更昂贵的正则表达式)

SELECT LAST_NAME AS A,
       CASE
       WHEN LAST_NAME LIKE '% JR'
         OR LAST_NAME LIKE '% SR'
         OR LAST_NAME LIKE '% II'
       THEN SUBSTR(LAST_NAME,-2)
       WHEN LAST_NAME LIKE '% III'
       THEN SUBSTR(LAST_NAME,-3)
       END AS SUFFIX
FROM   TBL_LAST_NAME
WHERE LAST_NAME IN ('MANFORTI JR','KRUMPAK III','PURDY II','MARRONE SR')

如果你想使用正则表达式,那么:

SELECT LAST_NAME AS A,
       REGEXP_SUBSTR(
         last_name,
         '\W(SR|JR|II|III)$',   -- Match a non-word character then suffix
                                -- at end-of-string
         1,                     -- Start from the 1st character
         1,                     -- Find the 1st match
         'i',                   -- Case insensitive
         1                      -- Return the 1st capture group
       ) AS suffix
FROM   TBL_LAST_NAME
WHERE LAST_NAME IN ('MANFORTI JR','KRUMPAK III','PURDY II','MARRONE SR')