- 至少出现一次。 和*号的区别在于
*
可以出现零次。
+
示例
line = "tpyyyyyyypbpr123"
regex_str = ".*?(p.+?p).*"
match_result = re.match(regex_str, line)
if match_result:
print(match_result.group(1))
运行结果
pyyyyyyyp
如果不加非贪婪问号的话就会出现pbp。
line = "tpyyyyyyypbpr123"
regex_str = ".*(p.+p).*"
match_result = re.match(regex_str, line)
if match_result:
print(match_result.group(1))
pbp
如果在前面加一个问号
line = "tpyyyyyyypbpr123"
regex_str = ".*?(p.+p).*"
match_result = re.match(regex_str, line)
if match_result:
print(match_result.group(1))
会出现
pyyyyyyypbp
- 指定出现几次
{1} 指定 出现1次
{2} 指定出现2次,以此类推
{2,} 出现两次及以上。
{2,5} 出现两到5次
示例
line = "tpyyyyyyypppbbpr123"
regex_str = ".*(p.{1}p).*"
match_result = re.match(regex_str, line)
if match_result:
print(match_result.group(1))
结果
ppp
示例
line = "tpyyyyyyypppbbpr123"
regex_str = ".*(py{2,7}p).*"
match_result = re.match(regex_str, line)
if match_result:
print(match_result.group(1))
结果
pyyyyyyyp
- 任意出现几次字符
[]
示例
line = "atpr123btpr"
regex_str = ".*?([abcd]tpr)"
match_result = re.match(regex_str, line)
if match_result:
print(match_result.group(1))
结果
atpr
- 空格
此处注意是小s
\s
- 不为空格
此处注意为大S,且只能有一个字符
\S
如果要表示 多个字符
\S+
- 表示任意汉字
[\u4e00-\u9FA5]
示例
line = "study in 南开大学"
regex_str = ".*?([\u4e00-\u9FA5]+大学)"
match_result = re.match(regex_str, line)
if match_result:
print(match_result.group(1))
结果
我在南开大学