阅读python文档

This commit is contained in:
asahi
2024-05-04 17:34:30 +08:00
parent baac0d4fee
commit 19325fe22b

View File

@@ -692,5 +692,73 @@ total 4
drwxrwxrwx 1 asahi asahi 4096 Feb 7 21:39 venv 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<prefix>.*) 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
类似javare提供了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 ']
```