Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've been looking up regular expression tutorials trying to get the hang of them and was enjoying the tutorial in this link right up until this problem: http://regexone.com/lesson/12

I cannot seem to figure out what the difference between "matching" and "capturing" is. Nothing I write seems to select the text under the "Capture" section (not even .*).

Edit: Here is an example for the tutorial that confuses me: (.* (.*)) is considered correct and (.* .*) is not. Is this a problem with the tutorial or something I am not understanding?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
535 views
Welcome To Ask or Share your Answers For Others

1 Answer

Matching:

When engine matches a part of string or the whole but does return nothing.

Capturing:

When engine matches a part of string or the whole and does return something.

-- What's the meaning of returning?

When you need to check/store/validate/work/love a part of string that your regex matched it before you need capturing groups (...)

At your example this regex .*?d+ just matches the dates and years See here

And this regex .*?(d+) matches the whole and captures the year See here

And (.*?(d+)) will match the whole and capture the whole and the year respectively See here

*Please notice the bottom right box titled Match groups

So returning....

1:

preg_match("/.*?d+/", "Jan 1987", $match);
print_r($match);

Output:

Array
(
    [0] => Jan 1987
)

2:

preg_match("/(.*?d+)/", "Jan 1987", $match);
print_r($match);

Output:

Array
(
    [0] => Jan 1987
    [1] => Jan 1987
)

3:

preg_match("/(.*?(d+))/", "Jan 1987", $match);
print_r($match);

Output:

Array
(
    [0] => Jan 1987
    [1] => Jan 1987
    [2] => 1987
)

So as you can see at the last example, we have 2 capturing groups indexed at 1 and 2 in the array, and 0 is always the matched string however it's not captured.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...