[英]How to replace last occurrence of a substring in MYSQL?
如何在 MYSQL 中用空白字符串替換最后一次出現的子字符串? 我在 MYSQL 中找不到任何這樣的直接函數
字符串: “美國公司國家公司”
搜索字符串: “公司”
預期輸出: “American Corp National”
有人可以建議嗎?
這是更短,更易讀:
SELECT TRIM(TRAILING 'Corp' FROM 'American Corp National Corp')
嘗試:
select reverse(concat(
left(reverse('American Corp National Corp'),
instr(reverse('American Corp National Corp'),reverse('Corp'))-1),
substr(reverse('American Corp National Corp'),
instr(reverse('American Corp National Corp'),reverse('Corp'))+
length('Corp')))) result
( SQLFiddle )
這是一個 SQL 查詢:
select CONCAT(SUBSTRING_INDEX('<TEST_STRING>','<String that you want to replace>',(length('<TEST_STRING>') - length(replace('<TEST_STRING>', '<String that you want to replace>', '')))),'<String to be replaced>',SUBSTRING_INDEX('<TEST_STRING>', '<String that you want to replace>', -1)) as test
這感覺是一種很糟糕的方法,但是... reverse
字符串,使用locate
搜索搜索字符串reverse
的第一次出現,然后計算非反轉字符串中的索引?
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_reverse
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_locate
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_char-length (很確定您需要使用它而不是長度以符合 unicode,但請檢查以確保!)
工作示例:
字符串:0123456789(char_length = 10)
搜索字符串:567(char_length = 3)
反向字符串:9876543210
反向搜索字符串:765
定位返回索引 = 2
實際字符串中的結尾索引 = 7 (char_length(string) - 1 - index -> 10 - 1 - 2)
實際字符串中的起始索引 = 5 (char_length(string) - 1 - (char_length(search string) - 1) - index -> 10 - 1 - (3 - 1) - 2)
在自己研究這個問題並閱讀了上面的答案后,我創建了以下函數來解決這個問題。 就我而言,我需要更改序列中的最后一個分隔符,例如,“Aap、Noot、Mies”將變為“Aap、Noot & Mies”:
CREATE DEFINER=`root`@`localhost` FUNCTION `change_last_substring`(
input_string text,
separator_old tinytext,
separator_new tinytext
) RETURNS text CHARSET utf8
BEGIN
set @output_string=
trim(
leading separator_new from
concat
(
left(input_string,length(input_string)-length(substring_index(input_string,separator_old,-1))-2),
separator_new,
substring_index(input_string,separator_old,-1)
)
);
RETURN @output_string;
END
該接受的答案並不能取代@FROM
與@TO
,它取代@FROM
空字符串。 如果您需要用@TO
替換@FROM
,這里是對該答案的修改:
SELECT reverse(
concat(
concat(
left(reverse(value),
instr(reverse(value), reverse(@FROM)) - 1),
@TO
),
substr(reverse(value),
instr(reverse(value), reverse(@FROM)) +
length(@FROM))))
FROM `table`
WHERE `value` like '%' + @FROM + '%'
注意額外的WHERE
值, like '%' + @FROM + '%'
,因為如果子字符串沒有出現在值中,這會刪除一個額外的字符,例如,在“ccc”中嘗試用“b”替換“a”會導致“抄”
更簡單可靠
CONCAT(SUBSTRING_INDEX('American Corp National Corp','Corp',2), "REPLACE_STRING" ,SUBSTRING_INDEX('American Corp National Corp','Corp',-1))
REPLACE_STRING 您可以使用替換字符串更改它或為替換為空。
如果您有最新版本的MySQL(> = V8) / MariaDB的(> = v10.0.5) ,則可以使用REGEXP_REPLACE
替換最后一次出現的needle
與replacement
,就像這樣:
REGEXP_REPLACE(haystack, "^.*needle", "\\1replacement")
這利用了*
的貪婪性。
如果你正在使用MySQL,並且知道(或可以計算)出現的次數,你可以使用可選的occurence
參數的REGEXP_REPLACE
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.