Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

regex - Regular Expression "Matching" vs "Capturing"

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...