Prateek Sharma
Prateek Sharma

Reputation: 31

Regular Expression in Python 3.0 not matching

If the string is I am Fine it is giving me output as I.

import re
string='hello I am Fine'
print(re.search(r'[A-Z]?',string).group())

Upvotes: 0

Views: 46

Answers (2)

Dhaval Simaria
Dhaval Simaria

Reputation: 1964

You can use the findall method.

From Python docs, section 7.2.5.6,

findall() matches all occurrences of a pattern, not just the first one as search() does.

In your case,

 >>> re.findall(r'[A-Z]',"hello I am Fine")
     ['I', 'F']

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

The ? specifies that the preceding character or class may or may not exist. When re.search starts searching the string, it does not find that class at the beginning of the string... and that is an acceptable match because of the ?. It is simply returning the empty string.

>>> re.search(r'[A-Z]?', 'hello I am Fine').group()
''

If you want it to find the first capital letter, don't use a ?:

>>> re.search(r'[A-Z]', 'hello I am Fine').group()
'I'

Upvotes: 0

Related Questions