Ajax1234
Ajax1234

Reputation: 71451

Python Upper and Lowercase Criteria in String Regex

I am trying to write a regular expression that scans a string and finds all instances of "hello", with both capital and lowercase letters. The problem is that while a simple

the_list = re.compile(r'hello')

would suffice for only "hello" in the string, I would like the expression to be able to find all versions of "hello" with both capitalized and lowercase letters, such as:

Hello, HELlo, hEllo, HELLO, heLLO, etc.

I have also tried:

the_list = re.compile(r'[a-z][A-Z]hello')

But no luck. Could anyone explain a better way to write this regular expression?

Upvotes: 8

Views: 28494

Answers (3)

cjonesrun
cjonesrun

Reputation: 146

This will ignore the case in the word you're searching for.

NOTE: re.I refers to IGNORECASE flag.

hello = re.compile(r'hello', re.I)

Upvotes: 1

Jay Bayona
Jay Bayona

Reputation: 41

You can also do it this way.

the_list = re.compile(r'hello(?i)')

Upvotes: 1

Taku
Taku

Reputation: 33714

Just use the IGNORECASE flag the re module provides:

the_list = re.compile(r'hello', flags=re.IGNORECASE)

If you want to write less, this is sufficient enough:

the_list = re.compile(r'hello', re.I)

Since re.I is just another way of writing re.IGNORECASE

Here's the documentation for re.IGNORECASE:

Perform case-insensitive matching; expressions like [A-Z] will match lowercase letters, too. This is not affected by the current locale and works for Unicode characters as expected.

Upvotes: 25

Related Questions