-
re.match(pattern, string)
:尝试从字符串开头匹配一个模式。如果字符串开头匹配模式,则返回匹配对象;否则返回None。import re pattern = r'hello' string = 'hello world' match_obj = re.match(pattern, string) if match_obj: print("Match!") else: print("No match")
out
Match!
-
re.search(pattern, string)
:在字符串中搜索模式,返回第一个匹配对象。如果没有匹配,则返回None。import re pattern = r'hello' string = 'world, hello' search_obj = re.search(pattern, string) if search_obj: print("Found!") else: print("Not found")
out
Found!
-
re.findall(pattern, string)
:在字符串中搜索模式,返回一个列表,包含所有匹配的子串。import re pattern = r'\d+' string = '12345,67890' matches = re.findall(pattern, string) print(matches)
out
['12345', '67890']
-
re.sub(pattern, repl, string)
:在字符串中用指定的替换字符串(repl)替换所有匹配的子串。import re pattern = r'fox' repl = 'dog' string = 'The quick brown fox jumps over the lazy dog' new_string = re.sub(pattern, repl, string) print(new_string)
out
The quick brown dog jumps over the lazy dog
-
re.split(pattern, string)
:根据模式将字符串分割为列表。import re pattern = r',\s*' string = 'apple,orange,banana,pear' lst = re.split(pattern, string) print(lst)
out
['apple', 'orange', 'banana', 'pear']
-
re.compile(pattern)
:将正则表达式编译为正则表达式对象,以便在后续匹配中重复使用。import re pattern = r'fox' string = 'The quick brown fox jumps over the lazy dog' regex = re.compile(pattern) match_obj = regex.search(string) if match_obj: print("Match!") else: print("No match")
out
Match!
-
re.fullmatch(pattern, string)
:尝试从字符串的开头到结尾匹配一个模式。如果整个字符串匹配模式,则返回匹配对象;否则返回None。import re pattern = r'hello' string = 'hello' match_obj = re.fullmatch(pattern, string) if match_obj: print("Match!") else: print("No match")
out
Match!
-
re.escape(string)
:将字符串中的特殊字符转义为字面值字符。import re string = 'Special characters: $ ^ * ( ) { } [ ] \\' escaped_string = re.escape(string) print(escaped_string) #out #Special\ characters:\ \$\ \^\ \*\ \(\ \)\ \{\ \}\ \[\]\ \\\\
-
re.subn(pattern, repl, string)
:与re.sub()类似,但返回一个元组,包含替换后的新字符串和替换的次数。import re pattern = r'fox' repl = 'dog' string = 'The quick brown fox jumps over the lazy dog' new_string, count = re.subn(pattern, repl, string) print(new_string) print("Replacements: ", count)
out
The quick brown dog jumps over the lazy dog,Replacements: 1
-
re.split(pattern, string, maxsplit=0, flags=0)
:与re.split()类似,但可以指定最大分割次数和标志。import re pattern = r',\s*' string = 'apple, orange, banana, pear' lst = re.split(pattern, string, maxsplit=2) print(lst)
out
['apple', 'orange', 'banana, pear']
python标准库(可在算法比赛使用的库)——re库
最新推荐文章于 2024-04-10 20:09:48 发布