在postgres中的数组列上使用regexp_replace

时间:2016-03-05 17:35:24

标签: sql regex postgresql

我正在尝试使用正则表达式更新数组列的每个元素中所有出现的值。

如果列不是text[]类型而是文本,我将使用此查询进行更新:

UPDATE my_table
SET my_column = regexp_replace(
    my_column, 'foo(\d+)', 'bar\1', 'g'
)

如何替换数组列中的每个元素?

2 个答案:

答案 0 :(得分:4)

我所知道的最简单的方法:

func lkFaceBookShare() {
    var serviceType: String = SLServiceTypeFacebook
    if !SLComposeViewController.isAvailableForServiceType(serviceType) {
        self.showUnavailableAlertForServiceType(serviceType)
    }
    else {
        var composeViewController: SLComposeViewController = SLComposeViewController.composeViewControllerForServiceType(serviceType)
        var keyWindow: UIWindow = UIApplication.sharedApplication().keyWindow
        var rect: CGRect = keyWindow.bounds
        UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, false, 0.5)
        self.view!.drawViewHierarchyInRect(rect, afterScreenUpdates: true)
        var viewImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        composeViewController.addImage(viewImage)
        var initalTextString: String = String(format: "Let's join together in the form of underground catch word go along with me!! Link: https://itunes.apple.com/us/app/uoi-hinh-bat-chu-gioi-duoi/id907330926?ls=1&mt=8")
        composeViewController.initialText = initalTextString
        var vc: UIViewController = self.view.window.rootViewController
        vc.presentViewController(composeViewController, animated: true, completion: { _ in })
    }
}

func showUnavailableAlertForServiceType(serviceType: String) {
    var serviceName: String = ""
    if serviceType == SLServiceTypeFacebook {
        serviceName = "Facebook"
    }
    else if serviceType == SLServiceTypeSinaWeibo {
        serviceName = "Sina Weibo"
    }
    else if serviceType == SLServiceTypeTwitter {
        serviceName = "Twitter"
    }

    var alertView: UIAlertView = UIAlertView(title: "Account", message: "Please go to the device settings and add a \(serviceName) account in order to share through that service", delegate: nil, cancelButtonTitle: "Dismiss", otherButtonTitles: "")
    alertView.show()
}

PostgreSQL太聪明了。可以使用SRF(设置返回函数,只是google)作为其他函数的参数。例如:

UPDATE my_table SET
  my_column = array(
    SELECT regexp_replace(unnest(my_column), 'foo(\d+)', 'bar\1', 'g'))

相同
select abs(unnest('{1,-2,3}'::int[]));

但更短。

返回

┌─────┐
│ abs │
╞═════╡
│   1 │
│   2 │
│   3 │
└─────┘

select abs(x) from unnest('{1,-2,3}'::int[]) as x; 只是将array(select ...)结果转换为数组的数组构造函数。

答案 1 :(得分:0)

使用CTE来mem[0]数组,对数组元素进行转换并聚合回一个数组,然后将其用于unnest()。假设您的表有一个主键:

UPDATE