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

如何在XPath中根据指定子字符串获取下划线分隔符的特定计数?

解决方案

没有直接满足需求的通用“现成函数”,但几乎所有编程语言都能通过字符串分割+索引查找的组合快速实现这个功能,逻辑简单且高效。核心思路是:把原字符串按下划线分割为非空元素的列表,再查找目标子串在列表中的位置(注意要从1开始计数)。

示例实现(Python)

# 目标字符串
target_str = "xtre_ghtr_juwed_tsdew_fgus_"
# 按下划线分割并过滤末尾空元素
split_parts = [part for part in target_str.split('_') if part]

def get_substring_position(target):
    try:
        # 列表索引从0开始,所以结果加1
        return split_parts.index(target) + 1
    except ValueError:
        # 子串不存在时的返回值,可按需调整
        return "子串不存在"

# 测试用例
print(get_substring_position("xtre"))  # 输出:1
print(get_substring_position("ghtr"))  # 输出:2
print(get_substring_position("fgus"))  # 输出:5

示例实现(JavaScript)

const targetStr = "xtre_ghtr_juwed_tsdew_fgus_";
// 分割后过滤空元素
const splitParts = targetStr.split('_').filter(part => part);

function getSubstringPosition(target) {
    const index = splitParts.indexOf(target);
    return index !== -1 ? index + 1 : "子串不存在";
}

// 测试用例
console.log(getSubstringPosition("xtre")); // 输出:1
console.log(getSubstringPosition("ghtr")); // 输出:2
console.log(getSubstringPosition("fgus")); // 输出:5

关键注意点

  • 原字符串末尾的下划线会导致分割后产生空元素,必须过滤掉,否则会干扰索引计算。
  • 如果需要处理重复子串的场景,index方法只会返回第一个匹配项的位置,若要获取所有位置,需要遍历列表收集索引。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:22:20