Explain this regex: (?: | {} I)

I am not new to regular expressions and I use them all the time. Also, I just don't get it. Here is the full expression:

/^(?:|{}I )am on (.+)\$/ 

I understand everything in this regular expression, except for the part (?:|{}I ) , and what is its relation in the context of the whole regular expression.

Any help would be greatly appreciated.

+4
source share
1 answer

This part corresponds to the subpattern at the very beginning of the line, which may be:

  • Nothing (the part between ?: And | empty) or

  • An opening brace { followed by a closing brace } , followed by the letter I , followed by a white space.

?: means that it does not capture, so the first captured subpattern is (.+) , not (?:|{}I ) .

Typically, the { and } characters are used in regular expressions to quantify a specific pattern (for example, \d{0,5} means 0 to 5 digits), but in this case they have no special meaning, since there are no digits or commas between them.

Regarding the entire regex, I assume that it should match a line starting with "am on ..." or "{} I am ...", although I have no idea why curly braces are needed or why $ hiding with \ in the end.

+8
source

Source: https://habr.com/ru/post/1401400/


All Articles