Source: https://yellorn.com/programming/regex-saying-hi
Given a sentence, s , write a RegEx to match the following criteria:
- The first character must be the letter H or h .
- The second character must be the letter I or i .
- The third character must be a single space (i.e.: \s ).
- The fourth character must not be the letter D or d .
Given n lines of sentences as input, print each sentence matching your RegEx on a new line.
Input Format
The first line contains an integer, , denoting the number of lines of sentences.
Each of the subsequent lines contains some sentence you must match.
Output Format
Find each sentence, s , satisfying the RegEx criteria mentioned above, and print it on a new line.
Sample Input
5
Hi Alex how are you doing
hI dave how are you doing
Good by Alex
hidden agenda
Alex greeted Martha by saying Hi Martha
Sample Output
Hi Alex how are you doing
Explanation
The first sentence satisfies the RegEx criteria set forth in the Problem Statement (starts with the case-insensitive word , followed by a space, followed by a letter that is not ), so we print the sentence on a new line.
The second sentence fails our RegEx criteria, as the second word/token starts with a (so we print nothing).
The third sentence fails our RegEx criteria, as it doesn’t start with an (so we print nothing).
The fourth sentence fails our RegEx criteria, as the third character in the sentence is not a space (so we print nothing).
The fifth sentence fails as our RegEx criteria, as the sentence does not start with the word (so we print nothing).
Testcase
Input
8
hI swimming prior lead control trial gram report island
hI sufficiently
hI emphasize stand retire commitment pencil accurate
generous painful age expense conscious
noise wind lover attractive song early environment hero walk
loss carelessly advantage
female
shop
Output
hI swimming prior lead control trial gram report island
hI sufficiently
hI emphasize stand retire commitment pencil accurate
Solution
import re
import sys
pattern = r"^hi\s(?!d)"
for _ in range(int(input())):
# text = sys.stdin.readline()
text = input()
found = re.search(pattern, text, flags=re.I)
if found:
print(text)
Comments
Post a Comment