Easy notes on how to use
import re
ptn = re.compile(r"hoge+") #Compiling is faster if you want to reuse it
ptn_with_capture = re.compile(r"(hoge)e*") #Use parentheses for capture
string = r"hogee_qwerty_hogeeeeee"
#Get the first part to match
first_matched_string = re.search(ptn, string).group()
print(first_matched_string)
# => hogee
#If you attach a capture, group(number)Get only that part
first_matched_string = re.search(ptn_with_capture, string).group(1)
print(first_matched_string)
# => hoge
#Get all matching parts in a list
matched_string_list = re.findall(ptn, string)
print(matched_string_list)
# => ['hogee', 'hogeeeeee']
#If you attach a capture, only the capture part will be acquired
matched_string_list = re.findall(ptn_with_capture, string)
print(matched_string_list)
# => ['hoge', 'hoge']
#Get all matching parts with an iterator
matched_string_iter = re.finditer(ptn, string)
print([ s.group() for s in matched_string_iter])
# => ['hogee', 'hogeeeeee']
#Split the string at the matching part
split_strings = re.split(ptn, string)
print(split_strings)
# => ['', '_qwerty_', '']
#Replace the matching part with another string
replace_with = r"→\1←" #Use what was captured with a backslash and a number.
substituted_string = re.sub(ptn_with_capture, replace_with, string)
print(substituted_string)
# => →hoge←_qwerty_→hoge←
#Minimum match
minimal_ptn = re.compile(r"h.*?e") # *Or?、+After the symbol that represents repetition, etc.?The minimum match with.
minimal_matched_string = re.search(minimal_ptn, string)
print(minimal_matched_string.group())
# => hoge
Recommended Posts