[英]Regex to extract key value by brackets
我想從[key] value
格式的文本中獲取鍵和值:
例如,
[AA] abcd 1234 !@#$ _+{}[]:"
blah blah
[abc-def] this is also value.
[BB]abcd defg
[CC] (can null)
而我的Python代碼是這樣的:
import re
text ='''
[AA] abcd 1234 !@#$ _+{}[]:"
blah blah
[abc-def] this is also value.
[BB]abcd defg
[CC]
'''
pattern = re.compile(this is what I want)
result = {m.group('field'):m.group('value') for m in pattern.finditer(text)}
如果值只有這樣一行
[AA] abcd 1234 !@#$ _+{}[]:"
[BB]abcd defg
[CC]
那么我可以在下面的正則表達式中使用,您可以看到https://regex101.com/r/rS8oM1/1
\[(?P<key>AA|BB|CC)\]\s*(?P<value>.*)
在應用正則表達式之前,只需排成一行即可使您的生活更輕松:
>>> text ='''
... [AA] abcd 1234 !@#$ _+{}[]:"
... blah blah
... [BB]abcd defg
... [CC]
... '''
>>> print(text)
[AA] abcd 1234 !@#$ _+{}[]:"
blah blah
[BB]abcd defg
[CC]
>>> newtext=''
>>> for line in text.split('\n'):
... newtext=newtext+('\n' if re.match('^\[\w\w\]', line) else '')+line
...
>>> print(newtext)
[AA] abcd 1234 !@#$ _+{}[]:"blah blah
[BB]abcd defg
[CC]
>>> for i in newtext.split('\n'):
... print(re.findall(r'^\[(\w\w)\](.*)$',i))
...
[]
[('AA', ' abcd 1234 !@#$ _+{}[]:"blah blah')]
[('BB', 'abcd defg')]
[('CC', '')]
>>>
Edit1:具有自定義輸入。
$ cat a.py
import re
text ='''
[AA] abcd
[abcd]
[BB]abcd defg
[CC]
'''
newtext=''
for line in text.split('\n'):
newtext=newtext+('\n' if re.match('^\[\w\w\]', line) else '')+line
for i in newtext.split('\n'):
print(re.findall(r'^\[(\w\w)\](.*)$',i))
$ python a.py
[]
[('AA', ' abcd[abcd]')]
[('BB', 'abcd defg')]
[('CC', '')]
$
我假設您只需要獲取鍵 (僅在行的開頭使用[AA]
或[BB]
或[CC]
)和一個值 (在三個替代鍵之后,在下一個鍵或字符串結尾之前的所有文本) )。
您可以使用基於脾氣暴躁的令牌的正則表達式,它充當字符 序列的 否定字符類的同義詞:
(?sm)^\[(?P<key>AA|BB|CC)\]\s*(?P<value>(?:(?!\n\[(?:AA|BB|CC)]).)*)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
(?:(?!\\n\\[(?:AA|BB|CC)]).)*
修飾的貪婪標記匹配任何不是\\n[AA]
或\\n[BB]
或\\n[CC]
。
(?sm)
是內聯修飾符:( (?s)
啟用DOTALL模式( .
開始匹配換行符),而(?m)
使^
匹配行的開頭,而不僅僅是字符串的開頭。
參見示例Python演示 :
import re
text ='''
[AA] abcd 1234 !@#$ _+{}[]:"
blah blah
[abc-def] this is also value.
[BB]abcd defg
[CC]
'''
pattern = re.compile(r'(?sm)^\[(?P<key>AA|BB|CC)\]\s*(?P<value>(?:(?!\n\[(?:AA|BB|CC)]).)*)')
result = {m.group('key'):m.group('value') for m in pattern.finditer(text)}
print(result)
# => {'AA': 'abcd 1234 !@#$ _+{}[]:"\nblah blah\n[abc-def] this is also value.', 'CC': '', 'BB': 'abcd defg'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.