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

Ruby中使用正则表达式匹配提取contract_addendum_1键及其对应值

Ruby匹配contract_addendum_1键值的解决方案

最优方案:直接解析JSON(推荐)

你提供的字符串本质是转义后的JSON结构,直接解析为Ruby哈希取值是最稳妥、不会出边界错误的方法:

require 'json'

# 你的原始字符串(注意你给出的内容里`investment_id\":102,\"inve,`属于截断笔误,修正为合法JSON后即可正常解析)
raw_str = "{\"month_day\":\"JulyYork\",\"state\":\"NY\",\"zip\":\"10104\",\"country\":\"US\",\"investment_id\":102,\"contract_addendum_1\":\"Pursuant to the Side Letter re: Assignment dated [June__, 2021 ] between Security\\n Sponsor 2021-1, LLC herein as \"Subscriber\", and FTF Lending, LLC herein as \"Borrower\" so be it\\n acknowledged that Subscriber purchased this Non-Recourse Borrower Payment Dependent Note and\\n immediately transferred all of it's right,set forth to US Issuer hey 2021-1\\n herein as \"Holder\". [Lawyers to add any additional wording if needed].\",\"subscriber_name\":\"Security Sponsor 2021-1, LLC\"}"

data_hash = JSON.parse(raw_str)
# 直接取对应值
target_value = data_hash["contract_addendum_1"]
# 完整键值对可以直接构造为 "contract_addendum_1" => target_value

正则匹配方案(仅特殊场景使用)

如果确实无法解析JSON必须用正则匹配,可使用以下正则:

# 正则表达式
target_regex = /"contract_addendum_1":"((?:[^"\\]|\\.)*)"/m
# 匹配结果
match_result = raw_str.match(target_regex)
# 完整键值对为 match_result[0],单独的值为 match_result[1]

原正则失效原因

你之前写的\\"contract_addendum_1\\":\\"([^"]+)失效的核心原因是:
[^"]+只要遇到双引号就会停止匹配,而contract_addendum_1的值里包含大量转义双引号\"(比如\"Subscriber\"),匹配到第一个转义双引号就直接中断,自然拿不到完整值。

新正则原理

  • (?:[^"\\]|\\.)* 是非捕获组,匹配两类内容:要么是不等于双引号、不等于反斜杠的任意字符,要么是反斜杠转义的任意字符(包括转义双引号、转义换行符等),可以完整覆盖整个值的内容直到遇到未转义的结束双引号
  • 末尾的m是Ruby正则的多行修饰符,保证元字符可以匹配换行符,应对值内的换行场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 12:45:03