1

The regular expression in question is

(\d{3,4}[.-]?)+

sample text

707-7019-789

My progress so far

(            )+  a capturing group, capturing one or more
 \d{3,4}         digit, in quantities 3 or 4
        [.-]?    dot (or something) or hyphen, in quantities zero or one <-- this is the part I'm interested in

From my understanding this should match 3 or 4 digit number, followed by a dot (or anything, since dot matches anything) or a hyphen, bundled in a group, one or more times. Why doesn't this matches a

707+123-4567

then?

Rook
  • 54,867
  • 44
  • 156
  • 233
  • 5
    `.` matches anything outside of `[]` - inside of `[]`, it's just a dot. – Blorgbeard Feb 21 '14 at 09:02
  • when you use . in [] it will match only dot. The [] remove the special meaning of. So in you you case you will match only 3 or 4 digits followed by . or - or empty string and this group should repeat one or more times – ssimeonov Feb 21 '14 at 09:03

3 Answers3

7

. in a character group [] is just a literal ., it does not have the special meaning "anything". [.-]? means "a dot or a hyphen or nothing", because the entire group is made optional with the ?.

deceze
  • 471,072
  • 76
  • 664
  • 811
  • 1
    This answer has been added to the [Stack Overflow Regular Expression FAQ](http://stackoverflow.com/a/22944075/2736496), under "Other". – aliteralmind Apr 10 '14 at 01:04
1

The brackets remove the functionality of the dot. Brackets mean "Range"/"Character class". Thus you are saying Choose from the list/range/character class .- You aren't saying choose from the list "anything"- (anything is the regular meaning of .)

woutervs
  • 1,507
  • 12
  • 27
  • 1
    I see now. Maybe better rephrase that "range" to "from the set of [.-] so it's either one or the other". – Rook Feb 21 '14 at 09:41
1
[.-]?

What this means literally:

character class [.-]

  • Match only one out of the following characters: . and - literally.

lazy quantifier ?

  • Repeat the last token between 0 and 1 times, as few times as possible.
Vasili Syrakis
  • 8,340
  • 1
  • 31
  • 51