0

Hi I am still a beginner and have been trying to figure out how to use regular expression on this string:

Name: Brenden Walski  

I want to get the value of the name or basically I want to get everything after the "Name: ". I am using python by the way.Please help. Thank You!

AlexR
  • 2,412
  • 16
  • 26
Nazariy
  • 717
  • 6
  • 23
  • 2
    You dont' need a regex for this. You can just split on a colon and the strip the output of that. `string.split(':').strip()` – b10n Sep 28 '14 at 18:26

1 Answers1

1

The regular expression way:

>>> import re
>>> s = "Name: Brenden Walski"
>>> re.findall(r'^Name:(.*?)$', s)[0]
' Brenden Walski'

The regular expression is ^Name:(.*?)$, which means:

  • ^ = "start of line"
  • Name: = the literal string "Name:"
  • (.*?) = "everything" - the () turns it in a capturing group, which means the match is returned
  • $ = "end of line"

The long way of saying it is "The start of line, followed by the characters "Name:", then followed by one or more of any printable character, followed by the end of line"

The "other" way:

>>> s.split(':')[1]
' Brenden Walski'

The "other" way, when the name might include a ::

>>> s[s.find(':')+1:]
' Brenden Walker: Jr'
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • why use a non-greedy match? `(.*?)$` is equivalent to `(.*)` when the `re.DOTALL` flag is not given. – isedev Sep 28 '14 at 18:31
  • and `(.*?)` does not mean everything... it only works that way because you have added `$` after it. Otherwise, it would match **nothing** (or the shortest sequence leading up to the following character). – isedev Sep 28 '14 at 18:37
  • You can remove the `$` (and of course `?`) and it would still work. However, this answer was not meant to be a crash course in regular expressions - besides, for this specific string I would just use split(). – Burhan Khalid Sep 28 '14 at 18:39
  • however, in your answer, you state `(.*?)` matches everything - this is misleading and technically incorrect, since it is the expression `(.*?)$` which matches everything to the end of the line. Since you used a non-greedy operator, the expression following it is important. – isedev Sep 28 '14 at 18:45
  • Okay, you can propose an edit to the question with your preferred explanation and I will accept it :) – Burhan Khalid Sep 28 '14 at 18:49