你可以试试这个正则表达式:
string_value:(?=(?:(?!attributes_cache).)*name: last_name)\s+\"(\w+)\".*?attributes_cache
解释
string_value:
匹配字符string_value:
- Positive Lookahead
(?=(?:(?!attributes_cache).)*name: last_name)
它向前看是否包含name: last_name
但不会超出 attributes_cache ,否则它可能与下一个可能具有名称的结果集重叠:last_name
\s+
匹配任何空白字符(等于 [\r\n\t\f\v ])
- 量词——匹配一次到无限次,尽可能多次,根据需要回馈(贪婪)
\"
从字面上匹配字符"
(区分大小写)
- 第一个捕获组
(\w+)
:\w+ 匹配任何单词字符(等于 [a-zA-Z0-9_])=> 这是您要捕获的文本。
捕获组 1 包含您要查找的文本。
虽然您没有描述编程语言,但以下示例是在 ruby 上完成的(运行它):
re = /string_value:(?=(?:(?!attributes_cache).)*name: last_name)\s+\"(\w+)\".*?attributes_cache/m
str = '\\- !ruby/object:DynamicAttribute
attributes:
resource_id: "1"
resource_type: Applicant
string_value: "Johnson1"
int_value:
id: "35533149"
date_value:
name: last_name
attributes_cache: {}
\\- !ruby/object:DynamicAttribute
attributes:
resource_id: "1"
resource_type: Applicant
string_value: "Michael"
int_value:
id: "35972390"
date_value:
name: first_name
attributes_cache: {}
\\- !ruby/object:DynamicAttribute
attributes:
resource_id: "1"
resource_type: Applicant
string_value: "Johnson2"
int_value:
id: "35533149"
date_value:
name: last_name
attributes_cache: {}'
# Print the match result
str.scan(re) do |match|
puts match.to_s
end