2013-10-11 56 views
1

我有以下格式数据在我的Postgres表:用于替换的SQL命令?

create table t (col1 character varying, col2 character varying, col3 character varying); 

    col1 col2 col3 
    <a> <b>  <c> . 
    <d> owl:g <h> . 
    dbp:h1 <k>  <l> . 

我需要替换任何空白occurence与http://yago-knowledge.org/resource/VARIABLE

owl: <http://www.w3.org/2002/07/owl#VARIABLE> 
    dbp: <http://dbpedia.org/ontology/VARIABLE> 

我知道这是可能实现的Python一样使用re.sub(r“<(。*?)>”,r“http://yago-knowledge.org/resource/\1”,col)

我转换后的数据如下所示:

<http://yago-knowledge.org/resource/a> <http://yago-knowledge.org/resource/b> <http://yago-knowledge.org/resource/c> 
<http://yago-knowledge.org/resource/d> <http://www.w3.org/2002/07/g>  <http://yago-knowledge.org/resource/h> 
<http://dbpedia.org/ontology/h1>   <http://yago-knowledge.org/resource/k> <http://yago-knowledge.org/resource/l> 

是否有可能使用SQL在postgres中实现相同的功能?此外,在COL3有每个值后点,是有可能使用SQL

编辑消除斑点:我尝试以下使用正则表达式:

regexp_replace('<a>', '.[<a]a.', '<http://yago-knowledge.org/resource/') 

然而,它似乎并没有工作。任何人都可以指出我错在哪里。

+1

看看'regexp_replace'在http://www.postgresql.org/docs/9.1/static/functions-string.html – Laurence

+0

@劳伦斯非常感谢您的帮助。然而,我无法理解regexp_replace('Thomas','。[mN] a。','M')中'mN'的含义。你可以请一个简短的例子帮助解释 –

+0

'[mN] a'是定义搜索条件的正则表达式。 –

回答

1

将它封装到函数中可能会更容易。这应该让你开始:

Create Function squirrel(col varchar) returns varchar as $$ 
begin 
    col = regexp_replace(col, ' \.$', ''); 
    col = regexp_replace(col, '<(.)>', '<http://yago-knowledge.org/resource/\1>'); 
    col = regexp_replace(col, 'owl:(.*)', '<http://www.w3.org/2002/07/owl#\1>'); 
    col = regexp_replace(col, 'dbp:(.*)', '<http://dbpedia.org/ontology/#\1>'); 

    return col; 
end; 
$$ Language plpgsql; 

Select 
    squirrel(col1) col1, 
    squirrel(col2) col2, 
    squirrel(col3) col3 
from 
    t 

Example Fiddle