Ruby 2.3.0正则提取certutil证书信息至数组的技术咨询
certutil -store MY Output in Ruby 2.3.0 Hey there! Let's work through this certificate extraction problem you're facing with Ruby 2.3.0. The core challenge is crafting a regex that reliably targets each certificate's start and end boundaries, and plays nice with Ruby's scan method as you want.
The Regex Solution
Here's the exact pattern you need, paired with the Ruby code to put it into action:
certificates = cert_util_output.scan(/^=============== Certificate \d+ ================(.*?)(?=\n\s*$|\z)/m).flatten
Breaking Down the Regex
Let's unpack each part to understand why it works for your use case:
^: Anchors the match to the start of a line, ensuring we only catch the exact certificate header (not a similar string buried mid-line).=============== Certificate \d+ ================: Matches the standard header line for each certificate, where\d+captures the certificate number (N).(.*?): A non-greedy capture group that grabs all content after the header, stopping as soon as it hits the end of the certificate block (avoids accidentally grabbing multiple certificates at once).(?=\n\s*$|\z): A positive lookahead that signals the end of a certificate block. It triggers on either:\n\s*$: A blank line (newline followed by zero or more whitespace characters, ending the line), which separates certificates.\z: The very end of the entire string, handling the edge case where the last certificate doesn't have a trailing blank line.
mmodifier: Enables multiline mode, so the.character matches newline characters—critical since each certificate spans multiple lines.
Practical Example
Suppose your cert_util_output looks like this (simplified):
=============== Certificate 1 ================ Subject: CN=Example Cert 1 Issuer: CN=Example CA Valid From: 01/01/2023 =============== Certificate 2 ================ Subject: CN=Example Cert 2 Issuer: CN=Another CA Valid From: 02/01/2023
Running the code above will return an array with two elements, each containing the full content of one certificate (excluding the separator blank lines between blocks).
Ruby 2.3.0 Compatibility Note
All regex features used here are fully supported in Ruby 2.3.0—no compatibility hoops to jump through. If you want to clean up any leading/trailing whitespace in each certificate block, you can add a quick .map(&:strip):
certificates = cert_util_output.scan(/^=============== Certificate \d+ ================(.*?)(?=\n\s*$|\z)/m).flatten.map(&:strip)
内容的提问来源于stack exchange,提问作者mobios

