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

Ruby新手如何提取字符串中指定分隔符前的子字符串?

Ruby提取字符串开头到指定字符的子字符串方法

针对你的需求,这里有几种适合初学者的简单实现方法:

方法1:用split分割后取首元素

split可按指定字符将字符串拆分为数组,直接取第一个元素就能得到目标子串:

string1 = "1.1.67.01-f9@92a47088f49d095f0"
result = string1.split('-').first
# 输出结果:"1.1.67.01"

方法2:通过index定位后切片

先找到-的索引位置,再用切片语法截取开头到该位置之前的内容:

string1 = "1.1.67.01-f9@92a47088f49d095f0"
dash_position = string1.index('-')
result = string1[0...dash_position]
# 输出结果:"1.1.67.01"

这里用0...dash_position是左闭右开区间,刚好不会包含-本身。

方法3:使用partition拆分

partition会把字符串拆成「匹配前内容、匹配字符、匹配后内容」三部分,取第一部分即可:

string1 = "1.1.67.01-f9@92a47088f49d095f0"
result = string1.partition('-').first
# 输出结果:"1.1.67.01"

也可以用解构赋值让逻辑更直观:

result, _, _ = string1.partition('-')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 07:50:29