Note that there are some explanatory texts on larger screens.

plurals
  1. POPerl regex meant to add trailing slash if there is none doubles existing slash
    text
    copied!<p>In source code I have to read (not from me) I found a regex that is not working as expected (or at least with what it does the code is not doing what it should).</p> <p>The Idea of the regex is to make sure the string it processes has exactly one slash at the end afterwards.</p> <p>So here we go:</p> <pre><code>$string =~ s/\/*$/\//g; # Add a trailing slash </code></pre> <p>I read this as "find any number of slashes at the end of the string (0 included) and replace them with a single slash". But this is not what happens.</p> <p>The regex <strong>doubles</strong> an/multiple existing trailing slash(es). So I end up with two slashes if there already is one or more. If there is none I get one (as it would be the idea).</p> <p>I can reproduce it with <a href="http://lumadis.be/regex/test_regex.php" rel="nofollow">Regex tester</a> for example. Just enter <a href="http://example.com/foo/" rel="nofollow">http://example.com/foo/</a> (and vary it with different slash count at the end) in the top box, the regex in the second, "/" as the replace pattern and hit "send".</p> <p>It seems to revolve around the regex also replacing "nothing" (or the line ending?) with a slash (so it replaces "nothing" with one slash and the existing slash with one slash which makes up for the two slashes I see...).</p> <p>I used</p> <pre><code>$string =~ s/\/{1,0}$/\//g; # Add a trailing slash </code></pre> <p>also but this only works if there is at least one slash from the beginning.</p> <p><strong>EDIT</strong></p> <p>Just in case anyone is wondering:</p> <pre><code>$string =~ s/\/*\z/\//g; # Add a trailing slash </code></pre> <p>produces the same thing.</p> <p>And here is a <a href="http://lumadis.be/regex/test_regex.php?id=1082" rel="nofollow">direct link to the test page</a></p>
 

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