python 中的正则表达式学习笔记

# 判断一个字符串是否在另外一个字符串中
# 方法一
str = 'php|java|python|javascript|html'
print('php' in str)  # True

# 方法二
import re
str = 'php|java|python|javascript|html'

result = re.findall('php',str)
print(result)  # ['php']

# ----------------------------------------

# 返回一个字符串中所有的数字
import re

str = 'php123java312python123javascript123html'
print(re.findall('\d', str)) # ['1', '2', '3', '3', '1', '2', '1', '2', '3', '1', '2', '3']

# ----------------------------------------

# 匹配指定字符
import re

str = 'abc,afc,adc,arc'
# 匹配是 abc 或者 afc的
print(re.findall('a[bf]c',str))  # ['abc', 'afc']
# 匹配不是 abc 或者 afc的
print(re.findall('a[^bf]c',str))  # ['adc', 'arc']

# ----------------------------------------

# 数量词
import re

str = 'pytho1python2pythonn0'
# * 匹配 0 次或者无限多次
print(re.findall('python*',str)) # ['pytho', 'python', 'pythonn']
# + 匹配 1 次或者无限多次
print(re.findall('python+',str)) # ['python', 'pythonn']
# ? 匹配 0 次或者 1 次
print(re.findall('python?',str)) # ['pytho', 'python', 'python']

# ----------------------------------------

# () 是匹配组的
str = 'PythonPythonPython'
print(re.findall('(Python){3}',str)) # [' ']

str = 'PythonPython'
print(re.findall('(Python){3}',str)) # []

str = 'PythonPythonPythonPython'
print(re.findall('(Python){3}',str)) # ['Python']

# ----------------------------------------

# 忽略大小写
str = 'PythonPHPc++'
print(re.findall('php',str,re.I)) # ['PHP']

# ----------------------------------------

# 匹配所有的字符, 加上 re.S 以后, . 表示匹配所有的字符, 包含了换行符 \n
# 原本 . 是匹配除了换行符 \n 之外其他的所有字符
str = 'PythonPHPc++'
print(re.findall('php',str,re.S)) 

# ----------------------------------------

# 字符串替换
str = 'c++PythonPHPc++'
print(re.sub("c\+\+", 'Go', str)) # GoPythonPHPGo
print(re.sub("c\+\+", 'Go', str, 1)) # GoPythonPHPc++

# 其中 re.sub() 中的第二个参数还可以接收一个函数, 如下
str = 'c++PythonPHPc++'
def deal_str(value):
  match = value.group()
    return '!!' + match + '!!'

print(re.sub("c\+\+", deal_str, str)) # !!c++!!PythonPHP!!c++!!


 

LBfunny7777    领取更多资料
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值