CodexBloom - Programming Q&A Platform

Regex scenarios to Extract Key-Value Pairs from a JSON-like String in Go

👀 Views: 68 💬 Answers: 1 📅 Created: 2025-06-13
regex golang string-manipulation Go

I'm working on a project and hit a roadblock. I'm stuck on something that should probably be simple... I'm trying to parse a string that resembles JSON but is actually just a formatted string with key-value pairs separated by commas and equal signs, like this: `key1=value1, key2=value2, key3=value3`. My goal is to use regex to extract these pairs into a map in Go. However, I'm working with issues with matching the keys and values correctly, especially when keys or values contain spaces. Here's the regex I've written so far: ```go re := regexp.MustCompile(`(\w+)\s*=\s*([^,]+)`) // Trying to match key=value pairs ``` When I run the following code: ```go input := "key1=value1, key2=value2, key3=my value with spaces" matches := re.FindAllStringSubmatch(input, -1) for _, match := range matches { fmt.Println(match[1], match[2]) } ``` I get the output: ``` key1 value1 key2 value2 key3 my value with spaces ``` The regex seems to work for the most part, but it's not capturing the values when they contain spaces correctly. Instead, it stops at the first space and considers it the end of the value. I’ve tried adjusting the regex by using `\s*` in different places, but that didn't help. Is there a more robust way to handle values that may contain spaces? Any suggestions on how to modify my regex to achieve the expected output? I'm using Go 1.19.2. What am I doing wrong?