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

正则表达式实现自定义属性文件转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 the CONSTANT[ prefix.
  • ([^\]]+): Captures the value inside the brackets (stops at the first closing ], so it handles values with spaces too, like CONSTANT[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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:28:17