-3

Using python shell:

namesRegex=re.compile(r'Agent (\w)\w*')
namesRegex.findall('Agent Alice gave the secret documents to Agent Bob.')

output:['A', 'B']

the regular expression confused, me aren't we supposed to get [Agent A ,Agent B] ?

namesRegex.sub(r'Agent \1*****','Agent Alice gave the secret documents to Agent Bob.')

output:'Agent A***** gave the secret documents to Agent B*****'

could someone explain to me the last output and how it's relation works and valid with last Regular expression ?

pygeek
  • 4,294
  • 1
  • 13
  • 28

1 Answers1

0

re.findall: If one or more groups are present in the pattern, return a list of groups.

You should replace Agent (\w)\w* by (Agent \w)\w* in case you keep the structure of the regex. If not, you only use Agent \w.

I also tried to test results on python.

import re

#case1
print("Case 1")
string = "Agent Alice gave the secret documents to Agent Bob."
regex = '(Agent \w)\w*'

match = re.findall(regex, string)
print(match)

#case2
print("Case 2")
string = "Agent Alice gave the secret documents to Agent Bob."
regex = 'Agent \w'

match = re.findall(regex, string)
print(match)

Result

Case 1
['Agent A', 'Agent B']
Case 2
['Agent A', 'Agent B']
Thân LƯƠNG
  • 2,269
  • 2
  • 9
  • 13