Skip to main content
 首页 » 编程设计

使用正则表达式解析python字符串

2025年05月04日22txw1958

给定一个字符串 #abcde#jfdkjfd,我怎样才能得到两个 # 之间的字符串?我还希望如果没有 # 对(意味着没有 # 或只有一个 #),该函数将返回 None.

请您参考如下方法:

>>> import re 
>>> s = "abc#def#ghi#jkl" 
>>> re.findall(r"(?<=#)[^#]+(?=#)", s) 
['def', 'ghi'] 

解释:

(?<=#)  # Assert that the previous character is a # 
[^#]+   # Match 1 or more non-# characters 
(?=#)   # Assert that the next character is a #