Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is not an anomaly: <code>.*</code> can match anything.</p> <p>You ask to replace all occurrences:</p> <ul> <li>the first occurrence does match the whole string, the regex engine therefore starts from the end of input for the next match;</li> <li>but <code>.*</code> also matches an empty string! It therefore matches an empty string at the end of the input, and replaces it with <code>a</code>.</li> </ul> <p>Using <code>.+</code> instead will not exhibit this problem since this regex cannot match an empty string (it requires at least one character to match).</p> <p>Or, use <code>.replaceFirst()</code> to only replace the first occurrence:</p> <pre><code>"test".replaceFirst(".*", "a") ^^^^^^^^^^^^ </code></pre> <p>Now, why <code>.*</code> behaves like it does and <em>does not match more than twice</em> (it theoretically could) is an interesting thing to consider. See below:</p> <pre><code># Before first run regex: |.* input: |whatever # After first run regex: .*| input: whatever| #before second run regex: |.* input: whatever| #after second run: since .* can match an empty string, it it satisfied... regex: .*| input: whatever| # However, this means the regex engine matched an empty input. # All regex engines, in this situation, will shift # one character further in the input. # So, before third run, the situation is: regex: |.* input: whatever&lt;|ExhaustionOfInput&gt; # Nothing can ever match here: out </code></pre> <p>Note that, as @A.H. notes in the comments, not all regex engines behave this way. GNU <code>sed</code> for instance will consider that it has exhausted the input after the first match.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload