BrainLikeADullPencil
BrainLikeADullPencil

Reputation: 11653

Reg expression: why "name" not returned as a match

The following regular expression returns "Gray" and "James" as matches. I don't understand why "Name" isn't a match. Can you explain?

"Name:  Gray, James"[/(\w+), (\w+)/]

Upvotes: 1

Views: 90

Answers (2)

John Woo
John Woo

Reputation: 263723

Here's an explanation how your regex worked

Match the regular expression below and capture its match into backreference number 1 «(\w+)»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the characters “, ” literally «, »
Match the regular expression below and capture its match into backreference number 2 «(\w+)»
   Match a single character that is a “word character” (letters, digits, and underscores) «\w+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

Gray, James
(\w+), (\w+)

Name does not follow comma.

Upvotes: 3

Robert Peters
Robert Peters

Reputation: 4104

match a word next to a comma no spaces "(\w+),"

match a word after a comma and a space ", (\w+)"

Upvotes: 0

Related Questions