2

示例文本:

\- !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: {}

目标:

我试图在“name”等于某个字符串的“string_value”之后提取值。假设它等于last_name。这些属性没有任何特定的顺序。我已经探索过使用捕获组,但我并没有走得太远。

对此的任何帮助将不胜感激。谢谢!

4

1 回答 1

2

你可以试试这个正则表达式:

string_value:(?=(?:(?!attributes_cache).)*name: last_name)\s+\"(\w+)\".*?attributes_cache

解释

  1. string_value:匹配字符string_value:
  2. Positive Lookahead(?=(?:(?!attributes_cache).)*name: last_name)它向前看是否包含name: last_name但不会超出 attributes_cache ,否则它可能与下一个可能具有名称的结果集重叠:last_name
  3. \s+匹配任何空白字符(等于 [\r\n\t\f\v ])
  4. 量词——匹配一次到无限次,尽可能多次,根据需要回馈(贪婪)
  5. \"从字面上匹配字符"(区分大小写)
  6. 第一个捕获组(\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
于 2016-12-11T07:09:55.943 回答