2
$\begingroup$

When you write regulair expression (regex) engines, how do you tell ....

if ? means zero or one

...or if...

? means begin non-capturing group

Some examples of regular expressions are shown below:

(https?|ftp)://([^/\r\n]+)(/[^\r\n]*)?
(?:https?|ftp)://([^/\r\n]+)(/[^\r\n]*)?
$\endgroup$

1 Answer 1

6
$\begingroup$

Logically, the ? symbol should not exist without a preceding group or character. This is evident as most Regular Expression Engines will error when presented with only a ?, or with an Expression that begins with ?.

When implementing an engine, one must keep reference to the previous token for the purposes of counting operators such as ? or *.

Thus, when an engine encounters a ?, if there is no preceding token, and they are in a group, then they can be sure that this is a special group, which then depends on the characters following the ?. ?: for non-capturing, ?# for comments, and so on.

Essentially, ? can perform two different things by simply being aware of the context in which it appears, rather than processing it "in a vacuum".

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .