0

In python, how can I make a regular expression that would match all capitalization combinations of a word, without formatting the data before hand. For example, let's say I want to match lines in a file that match the word name, however it is capitalized. That is, name could look like any of the following

Name
nAMe
NAme

etc.

user1876508
  • 12,864
  • 21
  • 68
  • 105
  • 1
    Relevant: http://stackoverflow.com/questions/500864/case-insensitive-python-regular-expression-without-re-compile – squiguy Mar 06 '13 at 00:08

3 Answers3

4

Make sure to pass the re.IGNORECASE option when calling your match, find or search.

For your example it'd be something like:

import re
re.search('name', 'Name', re.IGNORECASE)
re.search('name', 'nAMe', re.IGNORECASE)
re.search('name', 'NAme', re.IGNORECASE)
1

python re module has a flag re.IGNORECASE, it should be what you are looking for.

re.IGNORECASE

Perform case-insensitive matching; expressions like [A-Z] will match lowercase letters, too. This is not affected by the current locale.

http://docs.python.org/2/library/re.html

Community
  • 1
  • 1
Kent
  • 189,393
  • 32
  • 233
  • 301
0

If you are not going to use re.compile with re.IGNORECASE, you can do it this way:

string_of_pattern = r'(?i)name' # i means ignore case

This is useful when we have to pass a string. The doc is here:

(?iLmsux)

(One or more letters from the set 'i', 'L', 'm', 's', 'u', 'x'.) The group matches the empty string; the letters set the corresponding flags: re.I (ignore case), re.L (locale dependent), re.M (multi-line), re.S (dot matches all), re.U (Unicode dependent), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function.

Note that the (?x) flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined.

Andrew_1510
  • 12,258
  • 9
  • 51
  • 52