-1

Here is the text that I want to apply my code to:

text = From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008

and I am using this regular expression: y = re.findall('\S+?@\S+',text) so that I can output

'd@uct.ac.za' but instead it is returning 'stephen.marquard@uct.ac.za'. Can you please explain to me why the '?' is being ignored and how I could fix this code to get my desired result?

  • 2
    Why do you even use `+` if you want a single character? Why not just `\S@\S+`? – Tomerikoo Jun 19 '22 at 13:52
  • 1
    If you want to understand how greedy/non-greedy operators work, try your pattern with `stephen@marquard@`. Greedy will match until the second `@` while lazy/non-greedy will match until the first. See it [here](https://regex101.com/r/kjj2Nf/1) – Tomerikoo Jun 19 '22 at 14:05

2 Answers2

1

The non greedy ? works, but the regex matches from left to right and starts with a nin whitespace char \S Then it repeats that as least a possible until the @

If you want to match a sinle non whitespace char other than @

[^\s@]@[^\s@]+

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0

You can try this one on your given text,

.@.*\...

Regex demo given here