Let’s explain the regex:
/.../
- Those /
are used in Javascript to denote that what is inside them is a regex. Therefore, the real regex is the ^(?:(?:gatos?|cachorro):)?
.
^
- String start. This means that whatever is found has to be found at the beginning of the string, not in the middle of it.
(?: ... )
- It is a no-capture group. It is only used to group subexpressions. Regex allows captures with the ( ... )
, so that you can extract parts of the text that gives the match. The use of this ?:
disables the capture when you have no interest in it or when it could mess up other parts where you want the capture to be made. In your case, you have no interest in capturing parts, only the whole.
gatos?|cachorro
- That might be gato
or gatos
or cachorro
. The s?
means that the s
may or may not appear. The |
indicates alternatives. The (?: ... )
around serves to group it all so that the |
know where the alternatives begin and where they end.
:
(the last) - Means the character :
even.
The last ?
- means that whatever is before in the (?: ... )
may or may not appear. If it does not appear, match is given anyway.
This way, there are only four strings that this regex recognizes that must be anchored at the beginning of the string. They are:
(emptiness)
gato:
gatos:
cachorro:
Note that the end of the string is not checked. Thus, the use of gato:blabla
also gives a match. But as the start is checked, xgato:
no match.
I imagine the original context of this is something like this:
\^(?:(?:https?|ftp):)?\
That is, it is something that has some relation to the verification whether a piece of text is a link (if it starts with http:
, https:
or ftp:
). However, he continues to accept the case that there is none of this on account of the latter ?
.
This regex seems strange to me,
(?:
means that matches the pattern but does not capture or is an empty group. has a:
lost here =>):)?
.?
at the end means optional character, ie in the group can marrygato
orgatos
. There’s one at the end of the group ...– rray
I found this:http://regexr.com/ , tested with: "/(?: (?: cats?| dog):)? /", and in the text field: I typed several data (cats, cat, cat:, cats:, other data, dog...etc), pulled ' from the beginning of the search, also gives to test using the "grep" in the terminal, only you have to remove the '/ /', and in the case of the '(' put '(', and '|', '|', very grateful, I have to study further...
– WanderFS