在我的MySQL数据库中,我有一列UTF-8格式的字符串,例如,我想使用RegEx提取第一个字符。
假设一个RegEx仅提取以下字符:
ਹਮਜਰਣਚਕਨਖਲਨ
并给出以下字符串:
ਹੁਕਮਿ ਰਜਾਈ ਚਲਣਾ ਨਾਨਕ ਲਿਖਿਆ ਨਾਲਿ ॥੧॥
提取的唯一字符是:
ਹਰਚਨਲਨ
我知道要解决此问题将需要执行以下步骤:
我已经看过所有关于SO的类似问题/答案,但到目前为止,没有一个能够解决我的问题。
我终于在我的一个程序员朋友的帮助下实现了这一目标。我直接将以下代码粘贴到SQL
数据库的部分中PhpMyAdmin
:
delimiter $$
drop function if exists `initials`$$
CREATE FUNCTION `initials`(str text, expr text) RETURNS text CHARSET utf8
begin
declare result text default '';
declare buffer text default '';
declare i int default 1;
if(str is null) then
return null;
end if;
set buffer = trim(str);
while i <= length(buffer) do
if substr(buffer, i, 1) regexp expr then
set result = concat( result, substr( buffer, i, 1 ));
set i = i + 1;
while i <= length( buffer ) and substr(buffer, i, 1) regexp expr do
set i = i + 1;
end while;
while i <= length( buffer ) and substr(buffer, i, 1) not regexp expr do
set i = i + 1;
end while;
else
set i = i + 1;
end if;
end while;
return result;
end$$
drop function if exists `acronym`$$
CREATE FUNCTION `acronym`(str text) RETURNS text CHARSET utf8
begin
declare result text default '';
set result = initials( str, '[ੴਓੳਅੲਸਹਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਵੜਸ਼ਖ਼ਗ਼ਜ਼ਫ਼ਲ਼]' );
return result;
end$$
delimiter ;
UPDATE scriptures SET search = acronym(scripture)
只是为了解释最后一行:
scriptures
是我要更新的表search
是我在表格内部创建的用于存储结果的新空列scripture
是scriptures
表中的现有列,其中包含我要从中提取的所有字符串acronym
是先前声明的函数,该函数希望将每个单词的第一个字母与RegEx中的字符进行匹配 [ੴਓੳਅੲਸਹਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਵੜਸ਼ਖ਼ਗ਼ਜ਼ਫ਼ਲ਼]
因此,代码的最后这一行将遍历该列的每一行scripture
,对其应用功能acronym
并将结果存储在新search
列中。
完美的!正是我在找什么:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句