상세 컨텐츠

본문 제목

re 기초

Python

by techbard 2024. 12. 3. 13:15

본문

반응형

# re

 

import re

 

patterns = ['term1', 'term2']

 

text = "This is a string with term1, but not the other term"

 

if re.search('hello', 'hello world'):

print("Match was found.")

else:

print("No Match was found.")

 

match = re.search(patterns[0], text)

 

print(match.start())

print(match.end())

 

split_term = '@'

 

phrase = 'What is your email, is it hello@gmail.com?'

 

print(re.split(split_term, phrase))

 

print(re.findall('match', 'Here is one match, here is another match'))

 

# 결과

Match was found.

22

27

['What is your email, is it hello', 'gmail.com?']

['match', 'match']

 

# re

ingredient = "Kumquat: 2 cups"

import re

pattern_text = r'(?P<ingredient>\w+):\s+(?P<amount>\d+)\s+(?P<unit>\w+)'
pattern = re.compile(pattern_text)
match = pattern.match(ingredient)

print(match.groups())
print(match.group('ingredient'))
print(match.group('amount'))
print(match.group('unit'))

# 결과
('Kumquat', '2', 'cups')
Kumquat
2
cups
반응형

관련글 더보기

댓글 영역