-2

What is the difference between .* and (.*) in regular expressions?

From what I've seen,

AB.*DE 

and

AB(.*)DE 

appear to match the same things but I want to know if there are any differences so I use the correct one.

I need to be able to match any number of characters between AB and DE and even match if there isn't anything between them (ABDE).

If .* and (.*) mean the same thing, is there a "better" one to use in terms of standards/best practice?

hwnd
  • 69,796
  • 4
  • 95
  • 132
twbbas
  • 407
  • 3
  • 9
  • 19
  • The `.` matches any character not just a dot so `\.` would be necessary to capture the `.`. Now for the parenthesis that introduces a capture group, to capture parenthesis and the dot use `\(\.\)`. – Joe Jul 10 '14 at 17:25
  • __There is a reference for this type of question.__ [Reference - What does this regex mean?](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean) – Evan Davis Jul 10 '14 at 17:26
  • 1
    The only difference is that one has a capturing group to match and capture the subpattern between those two patterns. [`.*`](http://regex101.com/r/oZ4zQ2/1) means any character except a newline sequence (`0` or more times) `matching the most amount possible`. By placing a [capturing group](http://regex101.com/r/oZ4zQ2/2) around it, it simply captures the pattern so you can reference back to the captured match for later use. – hwnd Jul 10 '14 at 17:31

3 Answers3

3
  • .* Matches any character zero or more times.
  • (.*) - Matched characters are stored into a group for later back-referencing(any charcter within () would be captrued).
  • AB.DE Matches the string ABanycharDE. Dot represent any character except newline character.
  • AB(.)DE AB and DE are matched and the in-between character is captured.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

The parentheses indicate a capture group.

X3074861X
  • 3,709
  • 5
  • 32
  • 45
0

There is no difference. Both will match any character zero+ times. However, the capture group is considered better because it allows you to group together your conditions. This makes your regular expressions look nicer and more readable just like parenthesis in math equations make the equation look nicer.

BitNinja
  • 1,477
  • 1
  • 19
  • 25