示例文本:
\- !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: "Johnson"
int_value:
id: "35533149"
date_value:
name: last_name
attributes_cache: {}
目标:
我正在尝试提取“string_value”之后的值,其中“name”等于某个字符串。假设它等于last_name。这些属性没有任何特定的顺序。我已经探索过使用捕获组,但没有取得多大进展。
对此的任何帮助将不胜感激。谢谢!
最佳答案
您可以尝试这个正则表达式:
string_value:(?=(?:(?!attributes_cache).)*name: last_name)\s+\"(\w+)\".*?attributes_cache
string_value:
匹配字符string_value:
- 正向先行
(?=(?:(?!attributes_cache).)*name: last_name)
它会向前查看是否包含name: last_name
但会不要超出 attribute_cache ,否则可能会与下一个结果集重叠,该结果集的名称可能为:last_name \s+
匹配任何空白字符(等于 [\r\n\t\f\v ])- 量词 - 匹配一次和无限次,尽可能多次,根据需要回馈(贪婪)
\"
与字符"
字面匹配(区分大小写)- 第一个捕获组
(\w+)
:\w+ 匹配任何单词字符(等于 [a-zA-Z0-9_])=> 这是您要捕获的文本。
捕获组 1 包含您要查找的文本。
虽然您没有描述编程语言,但以下示例是在 ruby 上完成的 (run it):
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
关于正则表达式 匹配捕获组内的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41082559/