在PostgreSQL中用大写版本替换正则表达式匹配的文本 [英] Replacing regex matched text with uppercase version in Postgresql

查看:99
本文介绍了在PostgreSQL中用大写版本替换正则表达式匹配的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个带有某些单词的字符串,这些单词用星号包围,例如

Given a string with certain words surrounded by stars, e.g.

The *quick* *brown* fox jumped over the *lazy* dog

您能否将星号包围的单词转换为大写形式,即

can you transform the words surrounded by stars into uppercase versions, i.e.

QUICK BROWN狐狸跳过了LAZY狗

The QUICK BROWN fox jumped over the LAZY dog

在表 sentences的 sentence栏中给出文字,我可以标记/提取单词如下:

Given text in a column 'sentence' in table 'sentences', I can mark/extract the words as follows:

SELECT regexp_replace(sentence,'\*(.*?)\*','STARTUPPER\1ENDUPPER','g') FROM sentences;

但我第一次尝试使用大写转换不起作用:

but my first attempt at uppercase transforms doesn't work:

select regexp_replace(sentence,'\*(.*?)\*','' || upper('\1'),'g') from sentences;

我想过在用开始标记和结束标记替换星号后,使用substring()拆分部分,但是如果加注了多个单词,该操作将失败。

I thought of using substring() to split the parts up after replacing the stars with start and end markers, but that would fail if there was more than one word starred.

推荐答案

您可以创建PL / pgSQL函数,例如:

You can create a PL/pgSQL function like:

CREATE FUNCTION upper_asterisk(inp_str varchar)
RETURNS varchar AS $$
DECLARE t_str varchar;
BEGIN

  FOR t_str IN (SELECT regexp_matches(inp_str,'\*.+\*','g'))
  BEGIN
    inp_str := replace(inp_str, t_str, upper(t_str));
  END;

  RETURN inp_str;
END;
$$  LANGUAGE plpgsql;

(经过Havent测试,可能有错误)。

(Havent tested, may have bugs).

或使用任何可用的语言在DB内编写此类功能。

Or use any available language to write such function inside DB.

这篇关于在PostgreSQL中用大写版本替换正则表达式匹配的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆