正则表达式实现自定义属性文件转JSON键值对(完善方案)
Solution for Converting CONSTANT-style Key-Value Pairs to JSON
Got it, let's refine your regex to properly handle the whitespace around keys and equals signs. Here's a robust approach that meets all your requirements:
Regex Pattern
\s*([^\s=]+)\s*=\s*CONSTANT\[([^\]]+)\]\s*
Pattern Breakdown
Let's break down what each part does to make it clear:
\s*: Matches zero or more spaces/tabs before the key (handles leading whitespace around the key).([^\s=]+): Captures the actual key (any characters except spaces or equals signs, so it works even if keys have underscores/hyphens).\s*=\s*: Matches the equals sign with any number of spaces (or none) on either side.CONSTANT\[: Exact match for theCONSTANT[prefix.([^\]]+): Captures the value inside the brackets (stops at the first closing], so it handles values with spaces too, likeCONSTANT[my user name]).\]\s*: Matches the closing]plus any trailing whitespace (handles spacing between multiple key-value pairs).
Replacement String
Use this to format each match into a JSON-style pair:
"$1":"$2",
Step-by-Step Example
Input String:
USERNAME = CONSTANT[myUserName] PASSWORD = CONSTANT[mypwd]
After Global Replacement:
Make sure to enable the global replacement flag (usually g in regex engines) to process all pairs. You'll get:
"USERNAME":"myUserName", "PASSWORD":"mypwd",
Final Touch for Valid JSON:
Just trim the trailing comma and wrap the result in curly braces to get a proper JSON object:
{ "USERNAME":"myUserName", "PASSWORD":"mypwd" }
Quick Notes
- If your regex tool doesn't support global replacement, you can run the replace operation multiple times until no more matches are found.
- This pattern works for both single-line inputs (multiple pairs) and multi-line inputs (one pair per line).
内容的提问来源于stack exchange,提问作者RajKon
相关产品推荐
相关产品推荐

