0

I am dealing with a dirty data source that has some key value pairs I have to extract. for example:

First Name = John Last Name = Smith Home Phone = 555-333-2345 Work Phone = Email = john.doe@email.com Zip From = 11772 Zip To = 11782 First Name = John First Name = John

To extract the First Name, I am using this regular expression:

/First Name = ([a-zA-Z]*)/

How do I prevent multiple matches in the case where the First Name is duplicated as shown above?

Here is a version of this on Rubular.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
koa
  • 515
  • 6
  • 17

3 Answers3

3

match will only get the first match (you would use scan to get all):

str.match(/First Name = ([a-zA-Z]*)/).captures.first
#=> "John"

(given your string is in str)

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
0

[] will also give you the first match:

str[/First Name = ([a-zA-Z]*)/, 1]

The 1 means the first capture group

pguardiario
  • 53,827
  • 19
  • 119
  • 159
0

/^First Name = ([a-zA-Z]*)/

this will work too. just add ^ to indicate start of line

az7ar
  • 5,187
  • 2
  • 19
  • 23