Friday, April 29, 2011

How does this regex work and how do i make it repeat only 5 times?

What does this regex do? i know it replaces the filename (but not extension)

    Regex r = new Regex("(?<!\\.[0-9a-z]*)[0-9]");
    return r.Replace(sz, "#");

How do i make it only repeat 5 times? to make it convert "1111111111.000" to "11111#####.000" ?

From stackoverflow
  • Try changing the asterisk after the closing bracket to "{5}" (no quotes). This depends a bit on your regex environment's feature set, but that is a common syntax.

    acidzombie24 : That breaks it (the ext now becomes ###).
  • The regex matches a character (0 to 9) that is not preceded by a dot then any number of 0 to 9 or a to z's.

    The replace line is responsible for the multi replacements. So you want to use the Replace method the has an extra parameter count.

    so the code would look like:

     Regex r = new Regex("(?<!\\.[0-9a-z]*)[0-9]");
     return r.Replace(sz, "#", 5);
    
    Simeon Pilgrim : Not tested, but this should actually replace the first 5 digits, thus giving you '#####1111.000' which is not what you want. So go with Konrad's solution.
  • I havent' tried this but Have tried it, works: how about changing the general pattern to use a positive lookahead instead? That way, it should work:

    [0-9a-z](?=[0-9a-z]{0,4}\.)
    

    Basically, this finds any (alphanumeric) character followed by up to four other alphanumeric characters and a period. This might just work to match the last five characters in front of the period consecutively. It's hellishly inefficient though, and it only works with engines that allow variable-width lookahead patterns.

    Konrad Rudolph : Works for me in .NET.

0 comments:

Post a Comment