Source text:

a, a, a, a

http://regexr.com/3epef

Non-working option:

/\,$/ 

And this is also non-working:

 /,$/ 

But strangely, it finds the last character "a". With a comma, this does not work:

 /a$/ 

    2 answers 2

    The quantifier * is greedy enough to capture all the characters before the last character following it. Therefore, the expression is quite simple:

     /.*,/ 

    True, you did not indicate what to do next with the comma found, for example, we can capture it into a group .*(,) . If you want to count a comma as the whole match, then you can apply an explicit reference to the starting point of the match ( \K ), i.e. .*\K,

    Regexp101.com example

    As for your attempt, the symbol $ means the end of a line, the expression a$ means such a letter a after which there is not a single character. ,$ accordingly expects the most recent comma, however, after it is another a therefore the expression does not fit

    • On the same regexr.com, your expression found everything except the last comma. - ModaL
    • @ModaL Of course, you didn’t say what "Find a comma" means. The complete coincidence of the expression is everything to the point and the comma itself. But we can take the comma itself in parentheses and it will be captured in group 1. If you want the complete expression of the whole expression to be just a comma, you need to specify the point from which to consider the match .*\K,
    • can you just write an expression on regexr to highlight the last comma with a blue background? If not difficult. - ModaL
    • @ModaL .*\K, regex101.com/r/EcLAF6/1 and what didn’t suit you green - Mike
    • everything is fine. Thank you very much for your help :) - ModaL

    Maybe do this:

     (,)([^,]*$) 
    • Nearly. But your expression captured the last comma and all that followed. - ModaL