简体   繁体   English

从Oracle中的String中提取特定数据集

[英]Extract Specific Set of data from a String in Oracle

I have the string ' 1_A_B_C_D_E_1_2_3_4_5 ' and I am trying to extract the data ' A_B_C_D_E '. 我有字符串' 1_A_B_C_D_E_1_2_3_4_5 ',我正在尝试提取数据' A_B_C_D_E '。 I am trying to remove the _1_2_3_4_5 & the 1_ portion from the string. 我想从字符串中删除_1_2_3_4_51_部分。 Which is essentially the numeric portion in the string. 这本质上是字符串中的数字部分。 any special characters after the last alphabet must also be removed. 还必须删除最后一个字母后的任何特殊字符。 In this example the _ after the character E must also not be present. 在此示例中,字符E之后的_也必须不存在。

and the Query I am trying is as below 我正在尝试的查询如下

SELECT 
REGEXP_SUBSTR('1_A_B_C_D_E_1_2_3_4_5','[^0-9]+',1,1) 
from dual

The Data I get from the above query is as below: - 我从上述查询得到的数据如下: -

_A_B_C_D_E_

I am trying to figure a way to remove the underscore towards the end. 我试图找到一种方法来删除最后的下划线。 Any other way to approach this? 任何其他方式来解决这个问题?

Assuming the "letters" come first and then the "digits", you could do something like this: 假设首先出现“字母”然后是“数字”,你可以这样做:

select regexp_substr('A_B_C_D_E_1_2_3_4_5','.*[A-Z]') from dual;

This will pull all the characters from the beginning of the string, up to the last upper-case letter in the string ( .* is greedy, it will extend as far as possible while still allowing for one more upper-case letter to complete the match). 这将从字符串的开头拉出所有字符,直到字符串中的最后一个大写字母( .*是贪婪的,它将尽可能地扩展,同时仍然允许另外一个大写字母来完成比赛)。

I have the string '1_A_B_C_D_E_1_2_3_4_5' and I am trying to extract the data 'A_B_C_D_E' 我有字符串'1_A_B_C_D_E_1_2_3_4_5',我正在尝试提取数据'A_B_C_D_E'

Use REGEXP_REPLACE : 使用REGEXP_REPLACE

SQL> SELECT trim(BOTH '_' FROM
  2         (REGEXP_SUBSTR('1_A_B_C_D_E_1_2_3_4_5','[0-9]+', ''))) str
  3  FROM dual;

STR
---------
A_B_C_D_E

How it works: 这个怎么运作:

  1. REGEXP_REPLACE will replace all numeric occurrences '[0-9]+' from the string. REGEXP_REPLACE将替换字符串中的所有数字出现'[0-9] +' Alternatively, you could also use POSIX character class '[^[:digit:]]+' 或者,您也可以使用POSIX字符类'[^ [:digit:]] +'
  2. TRIM BOTH '_' will remove any leading and lagging _ from the string. TRIM BOTH '_'将从字符串中删除任何前导和滞后_

Also using REGEXP_SUBSTR : 还使用REGEXP_SUBSTR

SELECT trim(BOTH '_' FROM 
       (REGEXP_SUBSTR('1_A_B_C_D_E_1_2_3_4_5','[^0-9]+'))) str 
FROM dual;
STR
---------
A_B_C_D_E

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM