JAVA - 我想从下面的文本中获取键和值。有“[key] value”格式

JAVA - I want to get key and value from below text. There is "[key] value" format

我想从下面的文本中获取键和值。有[key] value格式

例如,

[AA] abcd 1234 !@#$ _+{}[]:"
blah blah
[abc-def] this is also value.
[BB]abcd defg
[CC] (can null)

试试这个

\[(?<key>[^]]+)]\s*(?<value>[^\n]+(?:\n[^[][^\n]+)*)

Regex demo

解释:
\:转义特殊字符sample
( … ): 捕获组 sample
?:一次或none sample
[^x]: 一个不是x的字符sample
+:一个或多个sample
\s: "whitespace character": space, tab, newline, carriage return, vertical tab sample
*:零次或多次sample
(?: … ): 非捕获组 sample

简单!

^\[([^]]+)\](.+)$

演示: https://regex101.com/r/zB0xC0/1

解释:

  1. ^\[([^]]+)\]^是字符串的开头。 () 是一个捕获组。 [^]]+ 是除 ].
  2. 之外的任何字符中的一个或多个
  3. (.+)$$是字符串锚点的结尾。所以基本上它匹配键后的其余字符串。

这会起作用

^(?:\[([^]]+)\])?(.*)$

Regex Demo