Regex以匹配标识符后()中的第一个单词+可选值



我有点不知所措,无法找到一个合适的(.Net)正则表达式来匹配/提取符合以下条件的字符串中的信息:

  • 输入字符串可能有可选的前导空格
  • Regex应仅在特定关键字位于输入字符串的最开始或上述空白之后时匹配
  • 此关键字后面可能跟有":"和/或一个或多个空格
  • 但是,要提取的第一个值/匹配应该是标识符之后的第一个单词,并且只有当它是字母数字字符时(允许使用"-"one_answers"_"字符)
  • 现在是棘手的部分:可选地,如果(..)值可用,则可能有一个或多个值(空格分隔)在括号内,紧跟在上面的匹配之后,这些值应该在单独的组中逐一匹配

因此,基本上可能会发生以下情况:

Sample #1:
----------
Identifier key_abc_1
----------
>> this should match 'key_abc_1'
Sample #2:
----------
    Identifier: key_abc_1 some other text after the key
----------
>> this should match 'key_abc_1'

Sample #3:
----------
Identifier: key_abc_1(AB CD EF) some other text after key with paranthesis
----------
>> this should match 'key_abc_1' and as a second group containing 'AB', 'CD' and 'EF'

Sample #4:
----------
    Identifier: key_abc_1 some other text after key with paranthesis (AB CD EF) some other text after key with paranthesis
----------
>> this should match 'key_abc_1' only
Sample #5:
----------
    Identifier: key_abc_1 (AB CD EF) some other text after
----------
>> this should also only match 'key_abc_1' only
Sample #6:
----------
key_abc_1(AB CD EF) some other text after but no identifier at the beginning
----------
>> this should not match at all!

到目前为止,Lookbacking让我匹配了key_abc_1,但将可选的()-值和其他约束转换为合适的正则表达式有点让我难以理解。也许有人知道如何正确/可靠地做到这一点,并能推动我朝着正确的方向前进。

作为包含"AB"、"CD"one_answers"EF"的第二组

使用这种模式

^s*Identifier:?s*([a-zA-Z0-9-_]+)(?:(([^)(]*)))?

演示

应在单独的组中逐一匹配

使用这种模式

^s*Identifier:?s*([a-zA-Z0-9-_]+)(?:(([^)( ]+)[ )])?|G(?!^)([^ rn)]+)[ )]

演示

最新更新