在python中使用正则表达式检测特定字符串
我有一个具有以下字符串结构的csv文件:在python中使用正则表达式检测特定字符串,python,python-3.x,regex,python-2.7,re,Python,Python 3.x,Regex,Python 2.7,Re,我有一个具有以下字符串结构的csv文件: Modem Switch (MMA-213-MML-NW-Match-New Year)(32655)(12532) Modem Switch3 (MMA-1234-431-NW-Match-New Month)(32655)(12532) Modem Switch3 (MMA-1234-431-NW-Match-New1 Month)(32655)(12532) Modem Switch3 (MMA-1234-431-NW-Match-New Mont
Modem Switch (MMA-213-MML-NW-Match-New Year)(32655)(12532)
Modem Switch3 (MMA-1234-431-NW-Match-New Month)(32655)(12532)
Modem Switch3 (MMA-1234-431-NW-Match-New1 Month)(32655)(12532)
Modem Switch3 (MMA-1234-431-NW-Match-New Month 2)(32655)(12532)
....
我想得到匹配后出现的任何字符串:
例如,预期结果共享如下:
New Year
New Month
New1 Month
New Month 2
使用以下代码无法获取我的相对字符串:
matches = re.findall(r'(Match-)(\w+)', inp, flags=re.I)
这项工作:
import re
inp = "Modem Switch3 (MMA-1234-431-NW-Match-New Month)(32655)(12532)"
matches = re.findall(r'Match-(.+?)\)', inp, flags=re.I)
给予
您还可以使用空格匹配以下所有单词字符,并使用单个捕获组
\bMatch-(\w+(?:[^\S\r\n]+\w+)*)
|
输出
['New Year', 'New Month', 'New1 Month', 'New Month 2']
或者要在括号之间匹配match-
之后的所有字符,可以使用除(
和)
之外的任何字符进行匹配
使用
re.findall(r'(?使用re.findall(r'\b匹配-([^)]+)”,inp,flags=re.I)
import re
regex = r"\bMatch-(\w+(?:[^\S\r\n]+\w+)*)"
s = ("Modem Switch (MMA-213-MML-NW-Match-New Year)(32655)(12532)\n"
"Modem Switch3 (MMA-1234-431-NW-Match-New Month)(32655)(12532)\n"
"Modem Switch3 (MMA-1234-431-NW-Match-New1 Month)(32655)(12532)\n"
"Modem Switch3 (MMA-1234-431-NW-Match-New Month 2)(32655)(12532)")
print(re.findall(regex, s))
['New Year', 'New Month', 'New1 Month', 'New Month 2']
\([^()]*\bMatch-([^()]+)\)
--------------------------------------------------------------------------------
(?<= look behind to see if there is:
--------------------------------------------------------------------------------
Match- 'Match-'
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
[^()]+ any character except: '(', ')' (1 or more
times (matching the most amount possible))