- 至少出現一次。 和*號的區別在於
*
可以出現零次。
+
示例
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))
結果
我在南開大學