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

Ruby中如何拆分固定规则的下划线拼接字符串提取对应字段

字符串拆分解决方案

因为你给出的三个字段的可选值都是固定枚举项,不存在拆分歧义,直接通过枚举值正则匹配即可实现精准提取,有两种实现方式可选:

方案1:按你提供的代码结构单独匹配三个字段

三个字段对应的正则分别如下:

  • country 正则:/^(sg|jp)/,匹配字符串开头的国家枚举值
  • verification_type 正则:/(?<=^(sg|jp)_)(myinfo|myinfo_with_address|default)/,通过后置断言匹配国家和下划线之后的校验类型枚举值
  • account_type 正则:/(personal|account_manager|beneficial_owner)$/,匹配字符串末尾的账号类型枚举值

适配你给出的代码结构的示例(以JS为例):

const str = "sg_myinfo_with_address_account_manager"
const result = {
  country: str.match(/^(sg|jp)/)[1],
  verification_type: str.match(/(?<=^(sg|jp)_)(myinfo|myinfo_with_address|default)/)[1],
  account_type: str.match(/(personal|account_manager|beneficial_owner)$/)[1]
}

方案2:一次性整串匹配(更高效,推荐)

直接用带分组的正则一次性提取三个字段,避免多次调用匹配方法,性能更高,也更容易维护:

完整正则

/^(sg|jp)_(myinfo|myinfo_with_address|default)_(personal|account_manager|beneficial_owner)$/

代码示例

const str = "sg_myinfo_with_address_account_manager"
const fullReg = /^(sg|jp)_(myinfo|myinfo_with_address|default)_(personal|account_manager|beneficial_owner)$/
const matchResult = str.match(fullReg)
const result = {
  country: matchResult[1],
  verification_type: matchResult[2],
  account_type: matchResult[3]
}

正则逻辑说明

  • ^和$分别匹配字符串的开头和结尾,确保整个字符串完全符合定义的格式
  • 三个()包裹的分组分别对应三个字段的枚举可选值,不存在拆分错误的可能
  • 后续如果需要新增三个字段的可选值,只需要在对应分组里用|拼接新的取值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:39:04