substring-before()用于提取分隔符前的字符串,适用于从XML/HTML中提取前缀信息,如路径、ID等;若分隔符不存在则返回空,且仅匹配首个分隔符,需结合substring-after()处理复杂结构,常用于网页数据清洗。

XPath的
substring-before()
substring-before()
substring-before(string, substring)
举个例子,如果你有一个字符串是
"user-ID-12345"
"user"
substring-before("user-ID-12345", "-ID")"user"
"C:/Users/Documents/report.pdf"
substring-before("C:/Users/Documents/report.pdf", "/report.pdf")"C:/Users/Documents"
它在数据清洗和结构化提取方面,是一个非常基础但又高效的工具。我个人觉得,很多时候我们获取到的数据都不是那么规整的,尤其是从网页上抓取下来的文本,往往会带有一些前缀或者标识符,这时候
substring-before()
substring-before()
substring-after()
这两个函数就像一对孪生兄弟,都是用来切割字符串的,但一个取前面,一个取后面。
substring-before()
substring-after()
它们的应用场景自然也是互补的。比如,你有一个商品编号是
"PROD_A12345"
"PROD"
substring-before("PROD_A12345", "_A")"A12345"
substring-after("PROD_A12345", "PROD_")在处理URL时,这两种函数也经常配合使用。比如,从
"https://example.com/products?id=123&category=books"
"example.com"
substring-after(., '://')
"example.com/products?id=123&category=books"
substring-before(., '/')
"example.com"
substring-before()
虽然
substring-before()
一个比较常见的挑战是,如果指定的
substring
substring-before()
substring-before("hello world", "xyz")另一个限制是,它只会查找并处理第一个匹配到的分隔符。这意味着,如果你的字符串中包含多个相同的分隔符,比如
"apple-banana-cherry"
substring-before(., "-")
"apple"
"banana"
"cherry"
substring-before()
substring-after()
tokenize()
此外,
substring-before()
substring-before("HelloWorld", "world")lower-case()
substring-before()
在网页抓取中,
substring-before()
<a href="/product/detail/PID-12345-sku-abc.html">...</a>
PID-12345
这时,你可以这样来构建你的XPath表达式:
//a[starts-with(@href, '/product/detail/')]/@href
href
substring-before()
substring-before(substring-after(//a[starts-with(@href, '/product/detail/')]/@href, 'PID-'), '-sku-')
让我分解一下这个思路:
//a[starts-with(@href, '/product/detail/')]/@href
href
/product/detail/
<a>
href
substring-after(..., 'PID-')
PID-
substring-after()
href
PID-
/product/detail/PID-12345-sku-abc.html
12345-sku-abc.html
substring-before(..., '-sku-')
12345-sku-abc.html
sku-
12345
substring-before()
这样一步步地剥离,就能精准地提取出你想要的数据。这种组合使用
substring-before()
substring-after()
以上就是XPath的substring-before()函数怎么用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号