用逗号格式化字符串

时间:2020-03-18 10:25:00

标签: sql postgresql

我得到的字符串输出为:package com.pck.entity; import javax.persistence.*; import java.util.*; @Entity @Table(name="ingredient") public class Ingredient{ @Column(name="ingr_name") private String ingrName; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "ingredient") private Set<RecipeIngredient> recipeIngrs; public Ingredient() {} public String getIngrName() { return ingrName; } public void setIngrName(String ingrName) { this.ingrName = ingrName; } public Set<RecipeIngredient> getRecipeIngrs() { return recipeIngrs; } public void setRecipeIngrs(Set<RecipeIngredient> recipeIngrs) { this.recipeIngrs = recipeIngrs; } }

我想将其转换为:A B C D

已经存在并且可以在PostgreSQL中实现它。

3 个答案:

答案 0 :(得分:1)

尝试一下:

select REPLACE('A B C D', ' ', ',')

并使用以下命令将A,B,C,D替换为A,B,C and D

select substring('A,B,C,D',1,
length('A,B,C,D')-position(',' in reverse('A,B,C,D'))) 
 || ' and ' || 
substring('A,B,C,D',length('A,B,C,D')-position(',' in reverse('A,B,C,D'))+2);

您可以将以上内容与replace结合使用,以使其成为单个查询。

答案 1 :(得分:1)

我将使用两步方法。第一步用逗号替换所有空格。然后使用正则表达式将AND替换为最后一个逗号:

regexp_replace(replace('A B C D',' ',','), '(.*)(,)(\w+)$', '\1 and \3')

Online example

答案 2 :(得分:0)

无需复杂化。
单个正则表达式函数可捕获每个元素,并让您随心所欲地进行操作。

select regexp_replace(mycol, '(\S)+\s+(\S+)\s+(\S)\s+(\S+)','\1,\2,\3 and \4')
from   mytab

-

+----------------+
| regexp_replace |
+----------------+
| A,B,C and D    |
+----------------+

SQL Fiddle

相关问题