Using uuid_or_null function that @JuliusTuskenis suggests you can simply do this:
ALTER TABLE table_name ALTER COLUMN col TYPE UUID USING uuid_or_null(col);
delete from table_name where col is null;
You have to define the function before that.
create function uuid_or_null(s text) returns uuid immutable AS
$$
begin
return s::uuid;
exception when others then
return null;
end;
$$ language plpgsql;
The way uuid_or_null
is built is quite generic and more or less a pattern for safe casting - try to cast and if it bangs then react accordingly. There are several SO threads using it.
You can also sanitize the table upfront and then alter column type like this:
delete from table_name
where col !~* '^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$';
ALTER TABLE table_name ALTER COLUMN col TYPE UUID USING col::UUID;