Regex - Match the last 10 characters at the end of file

  • hello. I need a better solution for this regex, that match the last 10 characters of file.

    My solution is this:


    (Each point represents a character). It is ok, but if I want to match the last 45 characters, It will take some time to gather 45 points.

    The second trouble is that my Regex formula above match the last 10 characters of the last line at the file, but only if the last line has at least 10 characters. But if I need to match the last 10 characters, and 5 characters are on the last line, and another 5 is on the penultimate line, will not match.

  • Try this

  • @morbac said:

    Try this

    no, doesn’t work at all :(

  • got it. this will work


  • Hello, Vasile and morbac,

    Again, Vasile, remember to be as accurate as possible. Don’t forget that regexes work at character’s level !!

    For instance, when you say :

    Match the last 10 characters at the end of file

    Do you mean :

    • case A : 10 standard or EOL characters, that is to say, normal characters AND \r and/or \r

    • case B : 10 standard characters, only

    • Moreover, you would like, seemingly, that this counting spread over, on consecutive lines !

    So, let’s suppose the your file :

    • Ends with the two following lines

    • These two lines are, both, followed by the Windows EOL characters \r\n

    • The second line begins with a space character


    Then, the regex (?s).{10}\z would match from the digit 8,followed by the EOL characters of the first line, itself followed by the string 9012, preceded by a space and followed by the EOL characters of that second line

    Indeed, the string 8\r\n 9012\r\n, composed of consecutive characters, which a space character before digit 9, is, exactly, ten characters long and ends the file !

    Now, if you prefer match the 10 standard characters of a file, without including any EOL character, ( and, sometimes, on consecutive lines ) ,
    I don’t think, at first sight, about a regex which can match such a selection ! This kind of goal needs a script language !

    Indeed, with our example, that selection would be split in two parts : the string 45678, on one hand and the string 9012, preceded by a space character, on the other hand

    As a possible work-around, I would :

    • Firstly, delete any EOL character of the file by the simple S/R : SEARCH = \R and REPLACE = EMPTY. So your file would have been changed in a long single line of text, without any EOL, at its end

    • Secondly, perform the simple SEARCH .{10}\z This time, you would match the exact string 45678 9012, with a space character, between the digits 8 and 9, which is 10 standard characters long, too !

    Best Regards


  • yes, I forgot to delete EOL character. Thanks ;)

Log in to reply