简体   繁体   English

REGEXP_SUBSTR从数字开始提取固定长度的字符串

[英]REGEXP_SUBSTR to extract fixed length string starting from a digit

Table A
ID     ID_Descr
1     'DUP 8002061286'
2     'DUP 8002082667  '
3     ' 8002082669 DUP'

I would like to extract the string from the ID_Descr field with the following conditions: 我想使用以下条件从ID_Descr字段中提取字符串:

  1. String always starts with 8 字符串始终以8开头
  2. String length is always 10 digits 字符串长度始终为10位数字

This means stripping everything to the right and left of the string (eg. '8002082669'). 这意味着剥离字符串左右两侧的所有内容(例如“ 8002082669”)。 How can I achieve this? 我该如何实现? Using REGEXP_SUBSTR? 使用REGEXP_SUBSTR?

I am using Oracle 11g. 我正在使用Oracle 11g。

Thanks! 谢谢!

Although you could use regexp_substr() for this, I would take a different approach. 尽管您可以regexp_substr()使用regexp_substr() ,但我将采用其他方法。 I would just look for the '8' using instr() and then take the next 10 characters: 我只想使用instr()查找'8' ,然后使用接下来的10个字符:

select substr(id_descr, instr(id_descr, '8'), 10)

This seems like the simplest solution. 这似乎是最简单的解决方案。

You could use REGEXP_SUBSTR() but a regex is an expensive operation so you would be much better off using SUBSTR() and INSTR() : 您可以使用REGEXP_SUBSTR()但是正则表达式是一项昂贵的操作,因此使用SUBSTR()INSTR()会更好:

SELECT SUBSTR(ID_Descr, INSTR(ID_Descr, '8'), 10) FROM tableA;

If you really wanted to use REGEXP_SUBSTR() you could do it as follows: 如果您确实想使用REGEXP_SUBSTR() ,则可以按照以下步骤进行操作:

SELECT REGEXP_SUBSTR(ID_Descr, '8.{9}') FROM tableA;

This would get 8 plus the following 9 characters ( . being the wildcard). 这将得到8加以下9个字符( .是通配符)。

Now if you wanted to match only digits, then REGEXP_SUBSTR() would probably be your best bet: 现在,如果你想匹配数字,然后REGEXP_SUBSTR()可能会是你最好的选择:

SELECT REGEXP_SUBSTR(ID_Descr, '8[0-9]{9}') FROM tableA;

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

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