gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:27:51 24 4
gpt4 key购买 nike

我正在尝试匹配出现在(长)字符串末尾的键值对。字符串看起来像(我替换了“\n”)

my_str = "lots of blah
key1: val1-words
key2: val2-words
key3: val3-words"

所以我希望匹配“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'

编辑:

基于 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)<p></p>

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

最佳答案

负零宽度先行是(?!pattern)

re module documentation page 的中途提到了它.

(?!...)

Matches if ... doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match 'Isaac ' only if it’s not followed by 'Asimov'.

因此您可以使用它来匹配键后的任意数量的单词,但不能使用类似 (?!\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)

哪个给

['key1: val1-words ', 'key2: val2-words ', 'key3: val3-words']

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

for match in matches:
print match

它将打印:

key1: val1-words
key2: val2-words
key3: val3-words

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

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

您可以使用如下方式将每个键/值对转换为字典:

pairs = dict([match.split(':', 1) for match in matches])

这样可以更轻松地仅查找所需的键(和值)。

更多信息:


关于python - 正则表达式:如何匹配字符串末尾的键值对序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5323703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com