简体   繁体   中英

teradata sql - regexp_substr to split on ' - '

I am somewhat new to Teradata. I am more familiar with Presto SQL, where split_part is available.

I'm looking to split a string on a space, hyphen, space (' - ').

Example: 'Wal-Mart - Target - Best Buy - K-Mart - Staples'

I'm used to using split_part(split_part(COLUMN, ' - ',2), ' - '), 1) to get Target, which ignores the hyphens in Wal-Mart and K-Mart because the hyphen is not preceeded and followed by a space.

But, I can't figure out how to get 'Target' with Teradata.
strtok() only seems to work with a single character, which isn't sufficient since I want to split on 3 (' - ').

Any help would be appreciated!

根据您的版本(14.0 或最新版本),您可以使用strtok来解析它

select strtok(oreplace('Wal-Mart - Target - Costco - K-Mart - Staples',' - ','|'),'|',2)

While not a direct answer, maybe it will help with the logic so at the risk of getting flamed I'm throwing it out here anyway. With a regex you should be able to first describe your pattern in plain language to help analyze and define what you really need to get. ie You want the 2nd occurrence of a string that is surrounded by the pattern space-dash-space. What if the pattern is at the start or end of the line? Let's revise. You want a specified occurrence of a string that is preceded by the start of the line optionally OR by the pattern space-dash-space, and is followed by space-dash-space OR the end of the line.

In Oracle it would look like this where the first '2' in the argument list means get the 2nd occurrence of the pattern and the 2nd '2' means return the 2nd remembered group (in parenthesis). The WITH statement just sets up the data. You would have to translate this regex to Teradata.

WITH tbl(str) AS (
  SELECT 'Wal-Mart - Target - Best Buy - K-Mart - Staples' FROM dual
)
SELECT REGEXP_SUBSTR(str, '(^?| - )(.*?)( - |$)', 1, 2, NULL, 2) retailer
FROM tbl;

RETAILER
--------
Target  
1 row selected.

Play with query here

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