java中从多行文本中提取键值对

java中从多行文本中提取键值对,java,regex,key-value,matcher,keyvaluepair,Java,Regex,Key Value,Matcher,Keyvaluepair,考虑以下多行字符串: This is multiline text that needs to be correctly parsed into key-value pairs, excluding all other information. Section One: First key = Value One Second key = Value Two Section Two: Third key = Value Three Fourth ke

考虑以下多行字符串:

This is multiline text that needs to be correctly parsed into key-value pairs, excluding all other information.

 Section One:
    First key = Value One
    Second key = Value Two

 Section Two:   
    Third key = Value Three
    Fourth key = Value Four
    Fifth key = Value Five

 Section Three:
    Sixth key = Value Six
    Seventh key = Value Seven
    Eighth key = Value Eight
换句话说,文本由一个“引言”(一些短语)组成,后面是多行,分为多个部分,每个部分都有一个“标题”(例如,
第一节
)和多个键值对,用
=
分隔

键可以包含除新行和
=
之外的任何字符,值可以包含除新行之外的任何字符

有时,文本中可能会出现其他不相关的行

需要一个正则表达式,它将导致
matched.find()
返回所有键值对组,并且只返回那些键值对组,跳过引言和节标题,以及任何其他没有键值对的行

理想情况下,不需要其他文本预处理或后处理

在这个用例中,逐行读取文本并进行相应的处理不是一个选项

类似于
(?:\r |\n)(\s*[^=\.]+)\s*=\s*(.+)
的模式非常接近,但它们仍然包含更多的需求


有什么想法吗?

你就快到了。只需将
\s*
更改为
*
,因为
\s
也匹配换行符

(?:\r|\n) *([^\n=\.]+)(?<=\S) *= *(.+)
输出:

Key : First key => Value : Value One
Key : Second key => Value : Value Two
Key : Third key => Value : Value Three
Key : Fourth key => Value : Value Four
Key : Fifth key => Value : Value Five
Key : Sixth key => Value : Value Six
Key : Seventh key => Value : Value Seven
Key : Eighth key => Value : Value Eight

或者我们也可以使用\s*包含选项卡。这就是为什么我告诉您添加
[\t]*
当然。某些节头后面有一个选项卡存在问题-出于某种原因,正则表达式使用节中的第一个键连接每个此类头。第一个版本更简单,与第二个版本产生相同的结果+已经有1个了,谢谢。真的\s符合新行吗?我的印象是没有。你是对的。然后(?:\r |\n)*可以替换为\s*。如果间距是恒定的,也可以尝试
(?m)(?间距不是恒定的,它不起作用。尽管如此,谢谢。:-)您可以详细说明如何逐行读取文本,并且在此用例中相应的处理不是一个选项吗?
Key : First key => Value : Value One
Key : Second key => Value : Value Two
Key : Third key => Value : Value Three
Key : Fourth key => Value : Value Four
Key : Fifth key => Value : Value Five
Key : Sixth key => Value : Value Six
Key : Seventh key => Value : Value Seven
Key : Eighth key => Value : Value Eight