<p>When you write regulair expression (regex) engines, how do you tell ....</p>
<blockquote>
<p>if <code>?</code> means <code>zero or one</code></p>
</blockquote>
<p>...or if...</p>
<blockquote>
<p><code>?</code> means <code>begin non-capturing group</code></p>
</blockquote>
<p>Some examples of regular expressions are shown below:</p>
<pre><code>(https?|ftp)://([^/\r\n]+)(/[^\r\n]*)?
(?:https?|ftp)://([^/\r\n]+)(/[^\r\n]*)?
</code></pre>

<syntax><compilers><regex>
When you write regex engines how do you know if question marks `?` mean zero or one of if they refer to non-capturing groups?
<p>Logically, the <code>?</code> 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 <code>?</code>, or with an Expression that begins with <code>?</code>.</p>
<p>When implementing an engine, one must keep reference to the previous token for the purposes of counting operators such as <code>?</code> or <code>*</code>.</p>
<p>Thus, when an engine encounters a <code>?</code>, 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 <code>?</code>. <code>?:</code> for non-capturing, <code>?#</code> for comments, and so on.</p>
<p>Essentially, <code>?</code> can perform two different things by simply being aware of the context in which it appears, rather than processing it &quot;in a vacuum&quot;.</p>

CC BY-SA 4.0
2023-05-29T00:22:31.917Z
2023-06-02T03:11:05.873Z
2023-06-02T03:11:05.873Z
ATaco
# When you write regex engines how do you know if question marks `?` mean zero or one of if they refer to non-capturing groups?
Posted by: username_0 on 2023-05-28
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]*)?
**Tags:** syntax compilers regex
---
## 1 answers
### Answer by username_1 on 2023-05-29. Score: 6
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".
---
