30

Is there any difference between (\w+)? and (\w*) in regex?

It seems the same, doesn't it?

mavis
  • 3,100
  • 3
  • 24
  • 32
爱国者
  • 4,298
  • 9
  • 47
  • 66

1 Answers1

34

(\w+)? and (\w*) both match the same (0..+inf word characters)

However, there is a slight difference:

In the first case, if this part of the regex matches "", the capturing group is absent. In the second case, it is empty. In some languages, the former manifests as a null while the latter should always be "".

In Javascript, for example,

/(\w*)/.exec("")  // ["", ""]
/(\w+)?/.exec("") // ["", undefined]

In PHP (preg_match), in the former case, the corresponding key is simply absent in the matches array: http://3v4l.org/DB6p3#v430

John Dvorak
  • 26,799
  • 13
  • 69
  • 83