You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PostgreSQL中使用substring函数提取字符串中的指定前缀内容

使用substring函数提取下划线前的目标前缀

针对你需要从类似atlngahpig001_to_atlngahpig002-GatewayCallStats的字符串中提取第一个_之前内容的需求,用substring函数实现的核心思路是先定位第一个下划线的位置,再截取从字符串开头到该位置的子串,以下是几种常见编程语言的实现方案:

JavaScript 实现

// 示例字符串
const targetStr = "atlngahpig001_to_atlngahpig002-GatewayCallStats";
// 找到第一个下划线的索引位置
const underscoreIndex = targetStr.indexOf('_');
// 截取从开头到下划线位置的子串(不包含下划线)
const result = targetStr.substring(0, underscoreIndex);

console.log(result); // 输出: atlngahpig001

Java 实现

public class PrefixExtractor {
    public static void main(String[] args) {
        String targetStr = "atlngahpig001_to_atlngahpig002-GatewayCallStats";
        // 获取第一个下划线的索引
        int underscoreIndex = targetStr.indexOf('_');
        // 截取前缀
        String result = targetStr.substring(0, underscoreIndex);
        
        System.out.println(result); // 输出: atlngahpig001
    }
}

边界情况处理

如果遇到字符串中没有下划线的极端情况,建议增加判断逻辑避免报错:

const targetStr = "someStringWithoutUnderscore";
const underscoreIndex = targetStr.indexOf('_');
// 若找不到下划线,返回原字符串,也可根据需求返回自定义默认值
const result = underscoreIndex !== -1 ? targetStr.substring(0, underscoreIndex) : targetStr;

这个方案逻辑简单直接,不管前缀是atlngahpig001还是其他类似格式的字符串,只要结构是[前缀]_to_xxx就能准确提取。

内容的提问来源于stack exchange,提问作者user13246642

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 20:27:27