From 19325fe22bb20e59ceb3dd1fda6737cc94b5bdfe Mon Sep 17 00:00:00 2001 From: asahi Date: Sat, 4 May 2024 17:34:30 +0800 Subject: [PATCH] =?UTF-8?q?=E9=98=85=E8=AF=BBpython=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- python/py.md | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/python/py.md b/python/py.md index 89330cd..4d59d0e 100644 --- a/python/py.md +++ b/python/py.md @@ -692,5 +692,73 @@ total 4 drwxrwxrwx 1 asahi asahi 4096 Feb 7 21:39 venv ``` +## 正则 +python通过re模块提供了正则表达式的支持 +### match +match方法定义如下所示 +```py +re.match(pattern, string, flags=0) +``` +match方法使用示例如下所示: +```py +import re +def main(): + match_res = re.match("(?P.*) father", "i am your father") + if match_res is None: + print("failed match") + return + print(match_res.group("prefix")) # i am your + print(match_res.group(0)) # i am your father + + +main() +``` + +### search +search方法定义如下所示 +```py +re.search(pattern, string, flags=0) +``` +search方法使用示例如下所示 + +### pattern +类似java,re提供了compile方法,返回正则编译后的pattern,并通过pattern执行操作 + +#### findall +`pattern.findall`方法会返回所有匹配的字符串 +```py +import re + + +def main(): + msg = '''although i use amd graphic card, i view it as a trash for its bad performance in ai. + nvidia is also trash because its crazy price, fuck amd and nvidia!''' + pattern = re.compile("(amd|nvidia)\\s+(graphic card)?") + search_res_list = pattern.findall(msg) + print(search_res_list) + + +main() + +# [('amd', 'graphic card'), ('nvidia', ''), ('amd', '')] +``` +#### finditer +`pattern.finditer`会返回所有匹配的match对象 +```py +import re + + +def main(): + msg = '''although i use amd graphic card, i view it as a trash for its bad performance in ai. + nvidia is also trash because its crazy price, fuck amd and nvidia!''' + pattern = re.compile("(amd|nvidia)\\s+(graphic card)?") + search_res_list = pattern.finditer(msg) + print([e.group(0) for e in search_res_list]) + + +main() + +# ['amd graphic card', 'nvidia ', 'amd '] +``` \ No newline at end of file