0

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())
2
  • If the sting is "I am Fine" it is giving me output as 'I'. Commented Dec 28, 2016 at 5:10
  • Welcome to SO Prateek. How I interpret the question is your regex is not matching all the Uppercase letter in your string and just fetching the first match that is 'I'. And please do mark whichever answer you find helpful as 'Accepted'. Commented Dec 28, 2016 at 6:36

2 Answers 2

1

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']
Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.