正则表达式:如何匹配字符串末尾的键值对序列

OG *_*ude 6 python regex key-value

我试图匹配出现在(长)字符串末尾的键值对.字符串看起来像(我替换了"\n")

my_str = "lots of blah
          key1: val1-words
          key2: val2-words
          key3: val3-words"
Run Code Online (Sandbox Code Playgroud)

所以我希望匹配"key1:val1-words","key2:val2-words"和"key3:val3-words".

  • 可能的密钥名称集是已知的.
  • 并非所有可能的键都出现在每个字符串中
  • 每个字符串中至少会出现两个键(如果这样可以更容易匹配).
  • val-words可以是几个单词.
  • 键值对只应在字符串末尾匹配.
  • 我正在使用Python re模块.

我刚在想

re.compile('(?:tag1|tag2|tag3):')

加上一些前瞻性断言的东西将是一个解决方案.我不能说得对.我该怎么办?

谢谢.

/大卫

真实示例字符串:

my_str = u'ucourt métrage pour kino session volume 18\nThème: O sombres héros\nContraintes: sous titrés\nAuthor: nicoalabdou\nTags: wakatanka productions court métrage kino session humour cantat bertrand noir désir sombres héros mer medine marie trintignant femme droit des femmes nicoalabdou pute soumise\nPosted: 06 June 2009\nRating: 1.3\nVotes: 3'
Run Code Online (Sandbox Code Playgroud)

编辑:

根据Mikel的解决方案,我现在使用以下内容:


my_tags = ['\S+'] # gets all tags
my_tags = ['Tags','Author','Posted'] # selected tags
regex = re.compile(r'''
    \n                     # all key-value pairs are on separate lines
    (                      # start group to return
       (?:{0}):            # placeholder for tags to detect '\S+' == all
        \s                 # the space between ':' and value
       .*                  # the value
    )                      # end group to return
    '''.format('|'.join(my_tags)), re.VERBOSE)

regex.sub('',my_str) # return my_str without matching key-vaue lines regex.findall(my_str) # return matched key-value lines

Mik*_*kel 8

负零宽度前瞻是(?!pattern).

它在re模块文档页面的中间部分提到了.

(?!...)

匹配如果......下一个不匹配.这是一个负面的先行断言.例如,Isaac(?!Asimov)只有在没有'Asimov'的情况下才会匹配'Isaac'.

因此,您可以使用它来匹配键后的任意数量的单词,但不能使用类似的东西来匹配键(?!\S+:)\S+.

完整的代码看起来像这样:

regex = re.compile(r'''
    [\S]+:                # a key (any word followed by a colon)
    (?:
    \s                    # then a space in between
        (?!\S+:)\S+       # then a value (any word not followed by a colon)
    )+                    # match multiple values if present
    ''', re.VERBOSE)

matches = regex.findall(my_str)
Run Code Online (Sandbox Code Playgroud)

这使

['key1: val1-words ', 'key2: val2-words ', 'key3: val3-words']
Run Code Online (Sandbox Code Playgroud)

如果使用以下方法打印键/值:

for match in matches:
    print match
Run Code Online (Sandbox Code Playgroud)

它将打印:

key1: val1-words
key2: val2-words
key3: val3-words
Run Code Online (Sandbox Code Playgroud)

或者使用您更新的示例,它将打印:

Thème: O sombres héros 
Contraintes: sous titrés 
Author: nicoalabdou 
Tags: wakatanka productions court métrage kino session humour cantat bertrand noir désir sombres héros mer medine marie trintignant femme droit des femmes nicoalabdou pute soumise 
Posted: 06 June 2009 
Rating: 1.3 
Votes: 3
Run Code Online (Sandbox Code Playgroud)

您可以使用以下内容将每个键/值对转换为字典:

pairs = dict([match.split(':', 1) for match in matches])
Run Code Online (Sandbox Code Playgroud)

这样可以更容易地只查找所需的键(和值).

更多信息: