How get all matching positions in a string?

前端 未结 3 1854
轻奢々
轻奢々 2021-01-29 14:46

I have a column flag_acumu in a table in PostgreSQL with values like:

\'SSNSSNNNNNNNNNNNNNNNNNNNNNNNNNNNNSNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN\'         


        
3条回答
  •  粉色の甜心
    2021-01-29 15:24

    This works too. And a bit faster I think.

    create or replace function findAllposition(_pat varchar, _tar varchar) 
    returns int[] as
    $body$
    declare _poslist int[]; _pos int;
    begin
    
    _pos := position(_pat in _tar);
    while (_pos>0)
    loop
    
        if array_length(_poslist,1) is null then
            _poslist := _poslist || (_pos);
        else
            _poslist := _poslist || (_pos + _poslist[array_length(_poslist,1)] + 1);
        end if;
    
        _tar := substr(_tar, _pos + 1, length(_tar));
        _pos := position(_pat in _tar);
    
    end loop;
    return _poslist;
    
    end;
    $body$
    language plpgsql;
    

    Will return a position list which is an int array.

    {position1, position2, position3, etc.}
    

提交回复
热议问题