正则表达式
Linux中的正则表达式
grep
awk
sed
正则表达式组成
普通文本、具有特殊意义的符号
Pycharm连接虚拟机
import re
data = 'Last login: Tue Mar 10 12:59:11 2020 from 192.168.1.10'
new_data = re.split('[:.]\s*',data)
print(new_data)
print(data.split(': '))
['Last login', 'Tue Mar 10 12', '59', '11 2020 from 192', '168', '1', '10']
['Last login', 'Tue Mar 10 12:59:11 2020 from 192.168.1.10']
# ?[a-zA-Z]+
# ?用来匹配单词前后可能出现的空格,[a-zA-Z]代表一个或多个英文字母
#匹配一个IP地址 192.168.1.10
#[0-9]{1.3}\.[0-9]{1.3}\.[0-9]{1.3}\.[0-9]{1.3}
上机练习
findall()
flags=re.IGNORECASE:忽略大小写
import re
data = 'Linux系统内置Python 2.7.5,我们安装了Python 3.8.1。'
print(re.findall('Python [0-9]\.[0-9]\.[0-9]', data,flags=re.IGNORECASE))
['Python 2.7.5', 'Python 3.8.1']
compile
re_obj = re.compile('Python [0-9]\.[0-9]\.[0-9]', flags=re.IGNORECASE)
print(re_obj.findall(data))
['Python 2.7.5', 'Python 3.8.1']
比较两种方法:
Linux操作:
[root@localhost ~]# tail -5 data.txt
9999996
9999997
9999998
9999999
10000000
两种方式读取:
findall:
import re
def main():
pattern = "[0-9]+"
with open('~data.txt') as f:
for line in f:
re.findall(pattern,line)
if __name__ == "main":
main()
compile:
import re
def main():
pattern = "[0-9]+"
re_obj = re.compile(pattern)
with open("~/data.txt") as f:
for line in f:
re_obj.findall(line)
if __name__ == "main":
main()
上传到Linux:
Linux运行:
[root@localhost ~]# cd /opt/
[root@localhost opt]# ls
rh 演示代码
[root@localhost opt]# cd 演示代码/
[root@localhost 演示代码]# ls
test_data_compile.py test_data_findall.py
[root@localhost 演示代码]# time python3 test_data_findall.py
real 0m0.021s
user 0m0.016s
sys 0m0.005s
[root@localhost 演示代码]# time python3 test_data_compile.py
real 0m0.018s
user 0m0.015s
sys 0m0.003s
相比之下compile方法读取更快一些!!!