简体   繁体   中英

SQL Regex Pattern, How to match only a specific variable between two characters? (see Sample Output)

I have this inputs:

John/Bean/4000-M100
John/4000-M100
John/4000

How can I get just the 4000 but note that the 4000 there will be change from time to time it can be 3000 or 2000 how can I treat that using regex pattern?

Here's my output so far, it statisfies John/400-M100 and John/4000 but the double slash doesnt suffice the match requirements in the regex I have:

REGEXP_REPLACE(REGEXP_SUBSTR(a.demand,'/(.*)-|/(.*)',1,1),'-|/','')

You can use this query to get the results you want:

select regexp_replace(data, '^.*/(\d{4})[^/]*$', '\1')
from test

The regex looks for a set of 4 digits following a / and then not followed by another / before the end of the line and replaces the entire content of the string with those 4 digits.

Demo on dbfiddle

The following will match any multiple of 1000 less than 10000 when its preceded by a slash:

\/[1-9]0{3}

To match any four-digit number preceded by a slash, not followed by another digit, such as 4031 in—

Sal_AS_180763852/4200009751_S5_154552/4031

—try:

\/\d{3}(?:(?:\d[^\d])|(?:\d$))

https://regex101.com/r/Am34WO/1

This would also work, unless you need any digit followed by three zeros. See it in action here, for as long as it lives, http://sqlfiddle.com/#!4/23656/5

create table test_table 
( data varchar2(200))
insert into test_table values('John/Bean/4000-M100')
insert into test_table values('John/4000-M100')
insert into test_table values('John/4000')

select a.*,
       replace(REGEXP_SUBSTR(a.data,'/\d{4}'), '/', '')
from   test_table a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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