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

如何去除XPath中括号内字符串的首尾多余空白字符?

如何去除XPath中括号内字符串的首尾空白(保留中间空格)

需求说明

处理一批XPath字符串,移除括号内引号包裹内容的首尾空白字符,但保留字符串中间的空格。

输入示例

'/a/b[b1=" a12s "]/c[c1="1a3 "]/d'
'/a/b[b1=" 12a6a"]/c[c1="  s23 "]/d'
'/a/b[b1="s9d  "]/c[c1=" 1 2 x "]/d'

期望输出

'/a/b[b1="a12s"]/c[c1="1a3"]/d'
'/a/b[b1="12a6a"]/c[c1="s23"]/d'
'/a/b[b1="s9d"]/c[c1="1 2 x"]/d'

解决方案:正则表达式匹配替换

用正则精准定位括号内的"..."区域,捕获前后固定部分和中间需要处理的内容,再去掉中间内容的首尾空白后拼接回去即可。

Python 实现示例

import re

def trim_xpath_quote_content(xpath):
    # 正则匹配规则:捕获括号前缀、引号内的有效内容、括号后缀
    pattern = re.compile(r'(\[.*?=")\s*(.*?)\s*("\])')
    # 替换时去掉首尾空白,保留中间内容和前后前缀后缀
    return pattern.sub(r'\1\2\3', xpath)

# 测试用例
test_xpaths = [
    '/a/b[b1=" a12s "]/c[c1="1a3 "]/d',
    '/a/b[b1=" 12a6a"]/c[c1="  s23 "]/d',
    '/a/b[b1="s9d  "]/c[c1=" 1 2 x "]/d'
]

for xpath in test_xpaths:
    print(trim_xpath_quote_content(xpath))

JavaScript 实现示例

function trimXpathQuoteContent(xpath) {
    return xpath.replace(/(\[.*?=")\s*(.*?)\s*("\])/g, '$1$2$3');
}

// 测试用例
const testXpaths = [
    '/a/b[b1=" a12s "]/c[c1="1a3 "]/d',
    '/a/b[b1=" 12a6a"]/c[c1="  s23 "]/d',
    '/a/b[b1="s9d  "]/c[c1=" 1 2 x "]/d'
];

testXpaths.forEach(xpath => console.log(trimXpathQuoteContent(xpath)));

正则规则说明

  • (\[.*?="):捕获从[开始到="的前缀部分(非贪婪匹配,避免跨多个括号)
  • \s*(.*?)\s*:匹配引号内的首尾空白,.*?捕获中间需要保留的内容(包括中间空格)
  • ("\]):捕获"]的后缀部分

替换时将首尾空白剔除,直接拼接前缀、中间有效内容和后缀即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:13:22