[英]Regex between match string
嘿大家我有一個問題。 我是正則表達式的新手,我發現它對匹配有點困惑。 假設我想在數字模式之間取元素。
['1.Ab2 C34 2.kj4 nsb', '1.Dog Cat4 2.Bird6 Trex5']
是否可以只取數字 1. 和 2. 之間的任何元素?
output = [[Ab2 C34], [Dog Cat4]]
使用re.findall
:
inp = ['1.Ab2 C34 2.kj4 nsb', '1.Dog Cat4 2.Bird6 Trex5']
matches = [re.findall(r'\b1\.\s*(.*?)\s*2\.', x)[0] for x in inp]
print(matches) # ['Ab2 C34', 'Dog Cat4']
使用search
嘗試這樣的事情。
import re
new = [[re.search('1.(.*)2.', s).group(1)] for s in ['1.Ab2 C34 2.kj4 nsb', '1.Dog Cat4 2.Bird6 Trex5']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.