python-regexHow to use regex flags in Python?
Regex flags are used to modify the behavior of a regular expression search in Python. Flags can be specified in the re.compile()
function using the re.IGNORECASE
or re.I
flag to ignore case when matching strings.
Example code
import re
pattern = re.compile(r'\w+', re.I)
string = 'Hello World'
match = pattern.search(string)
print(match.group())
Output example
Hello
Code explanation
import re
: imports there
module which contains there.compile()
function.pattern = re.compile(r'\w+', re.I)
: creates a regular expression pattern object using there.compile()
function and there.I
flag to ignore case when matching strings.string = 'Hello World'
: creates a string to search.match = pattern.search(string)
: searches the string for a match using the pattern object.print(match.group())
: prints the matched string.
Helpful links
More of Python Regex
- How to match a plus sign in Python regex?
- How to match a URL using Python regex?
- How to match whitespace in Python regex?
- How to replace all using Python regex?
- How to match a UUID using Python regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match HTML tags with regex in Python?
- How to replace in a file using Python regex?
- How to get all matches from a regex in Python?
- How to use word boundaries in Python Regex?
See more codes...