Regular expression MCQ and practice problem

some regex questions for you all to test your knowledge and another question for you to practice.

 1. What will be the output of the following Python code?
   re.sub('evening', 'morning', 'good morning')

  a) ‘good evening’
  b) ‘good morning’
  c) ‘morning’
  d) ‘evening’

2. The expression a{5} will match _____________ characters with the previous regular expression.
  a) 5 or less
  b) exactly 5
  c) 5 or more
  d) exactly 4

3. What does the function re.search do?
  a) such a function does not exist
  b) matches a pattern at the start of the string
  c) matches a pattern at any position in the string
  d) none of the mentioned

4. What will be the output of the following Python code?
   re.split('[a-c]', '0a3B6', re.I)
  a)  Error
  b)  [‘0', '3', '6]
  c) [‘a’, ‘B’]
  d) [‘0’, ‘3B6’]

5. Which of the following characters matches the pattern only at the end of the string? 
  a) B
  b) Z
  c) I
  d) E

Practice problem. 
extract the financial year, Quarter and cost from the following text using regex. 

" The gross cost of operating lease vehicles in FY2021 Q1- was $4.85 billion.
In previous quarter. i.e. FY2020 Q4 it was $3 billion. "

I hope you find it informative.

2 Likes

1.b
2.b
3.b
4.d
5.d

FY=re.findall(‘\d{4}’,string)
Q=re.findall(‘Q\d’,string)
cost=re.findall(‘^$.+(billion)$’,string)

3 Likes

1__>>> (B)
2__>>> (B)
3__>>> (C)
4___>>>(D)
5__>>>> (B)

MCQ Answer

2 Likes

if you wanted to get all the matching strings, we can use regular brackets to collect them all inside a tuple. This is a method i have tried.

you can ask if there are any doubts in the above code. also post down below if you have other codes for the problem.