如何利用指定正则表达式从实体数组的字符串字段构建记录集合?
Extract Structured Records from JSON Using Your Regular Expression
Alright, let's turn that JSON array into a neat collection of structured records using your regex. First, let's clarify what each capture group in your pattern actually extracts:
- Group 1: The full GUID (e.g.,
a40a5e5c-98b3-45ae-d6a3-924b31d8712a) - Group 3: The resource type (e.g.,
article,book) - Group 4: The resource name (e.g.,
test,test2) - Group 5: The version timestamp (e.g.,
1521246543034)
(Group 2 is a nested capture for individual GUID segments, so we can ignore that for our final records.)
I’ve added ^ and $ anchors to your regex to ensure we only match complete, valid paths—this prevents partial matches on truncated entries like the third item in your array.
Example Implementation (JavaScript)
Here’s a practical way to process your JSON array into structured records:
// Updated regex with anchors for full-string matching const pathRegex = /^\/publication\/(([a-f0-9]+\-)+[a-f0-9]+)\/(.*?)\/(.*?);version=(\d*)$/; // Your input JSON array const inputJson = [ {"data": "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/article/test;version=1521246543034"}, {"data": "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/book/test2;version=1520623346891"}, {"data": "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/cata..."} ]; // Process each item to extract records const structuredRecords = inputJson.map(item => { const match = item.data.match(pathRegex); if (match) { return { guid: match[1], type: match[3], name: match[4], version: match[5] }; } else { // Handle invalid/truncated entries gracefully return { originalData: item.data, status: "Invalid or truncated path format" }; } }); // Log the result console.log(structuredRecords);
Output
Running this code will produce the following clean collection:
[ { guid: "a40a5e5c-98b3-45ae-d6a3-924b31d8712a", type: "article", name: "test", version: "1521246543034" }, { guid: "a40a5e5c-98b3-45ae-d6a3-924b31d8712a", type: "book", name: "test2", version: "1520623346891" }, { originalData: "/publication/a40a5e5c-98b3-45ae-d6a3-924b31d8712a/cata...", status: "Invalid or truncated path format" } ]
Quick Notes
- The
mapmethod iterates over every item in your JSON array, applying the regex to extract values. - Valid entries get converted into a structured object with clear, readable keys.
- Truncated or invalid paths are flagged so you can review or handle them later.
内容的提问来源于stack exchange,提问作者App2015
相关产品推荐
相关产品推荐

