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

如何将正则命名组哈希赋值给哈希值并解析用户数据生成目标哈希

Solution Using Ruby (Regex Named Groups + Hash Manipulation)

Got it, let's tackle this problem step by step—Ruby is a great fit here because it has native support for regex named capture groups and straightforward hash manipulation, which aligns perfectly with your needs.

Step 1: Define Input Data and Regex Pattern

First, we'll set up the raw input string and craft a regex with named capture groups to map each field directly to the keys in your target structure. This pattern will match every line of the pipe-separated data:

input_data = "1111|John|Smith|32\n2222|Sam|Adams|25\n3333|Chris|Stevens|30\n"

# Regex with named groups for each user field
user_pattern = /^(?<IdNumber>\d+)\|(?<Name>[^\|]+)\|(?<LastName>[^\|]+)\|(?<Age>\d+)$/

Step 2: Build the Nested Hash

Next, we'll iterate over each non-empty line of the input, run the regex match, and assign the named capture results directly to our final hash (using the user's ID as the top-level key):

result_hash = {}

# Split input into lines, skip empty lines (from trailing newline)
input_data.split("\n").reject(&:empty?).each do |line|
  # Run the regex match on the line
  match_result = user_pattern.match(line)
  next unless match_result # Skip lines that don't follow the format

  # Extract the named captures as a ready-to-use hash
  user_details = match_result.named_captures

  # Assign the user details hash to our result, keyed by their ID
  result_hash[user_details["IdNumber"]] = user_details
end

Step 3: Verify the Output (Convert to JSON)

To confirm we've built the exact structure you want, we can convert the hash to JSON:

require 'json'
puts result_hash.to_json

This will output the JSON structure you specified:

{
  "1111": {
    "IdNumber": "1111",
    "Name": "John",
    "LastName": "Smith",
    "Age": "32"
  },
  "2222": {
    "IdNumber": "2222",
    "Name": "Sam",
    "LastName": "Adams",
    "Age": "25"
  },
  "3333": {
    "IdNumber": "3333",
    "Name": "Chris",
    "LastName": "Stevens",
    "Age": "30"
  }
}

Quick Notes

  • The named_captures method gives us a pre-built hash of our regex groups—no need to manually map values to keys!
  • We skip empty lines to avoid errors from the trailing newline in your input string.
  • If you're using another language (like Python), the core logic is the same: use regex named groups, loop through lines, and build a nested dictionary/hash with the ID as the top key.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:11:25