简体   繁体   中英

Is there a way in Mysql to extract string from second occurrence of a dynamic length

In MySql DB, I have a column of string like

xx-11|Hello Shrishti|@KFC near you|Bhopal|...

with varying fields concatenated by the pipe operator '|'. Sometimes there are no extra fields like "xx-22|Hello Chandu" .

I want to extract the string after the second occurrence of '|'if extra fields are present, and an empty string if no extra fields are present.

Can anyone please help me with any logic. I have tried INSTR , SUBSTR , etc. but I could not come up with the proper solution.

Thanks in advance.

Use two calls to LOCATE to get the position of the 2nd | , and SUBSTR()` to get everything after that.

SUBSTR(columnName, LOCATE('|', columName, LOCATE('|', columName)+1)+1)

If you're using MySQL 8.x, you can use REGEXP_REPLACE()

REGEXP_REPLACE(columnName, '^[^|]*\\|[^|]*\\|', '')

The regexp matches from the beginning of ^ to the second | .

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