Simple Regex: match everything until the last dot

前端 未结 3 2088
一生所求
一生所求 2021-02-08 00:48

Just want to match every character up to but not including the last period

 dog.jpg     -> dog
 abc123.jpg.jpg -> abc123.jpg

I have tried

3条回答
  •  无人及你
    2021-02-08 01:03

    Regular expressions are greedy by default. This means that when a regex pattern is capable of matching more characters, it will match more characters.

    This is a good thing, in your case. All you need to do is match characters and then a dot:

    .*\.
    

    That is,

    .   # Match "any" character
    *   # Do the previous thing (.) zero OR MORE times (any number of times)
    \   # Escape the next character - treat it as a plain old character
    .   # Escaped, just means "a dot".
    

    So: being greedy by default, match any character AS MANY TIMES AS YOU CAN (because greedy) and then a literal dot.

提交回复
热议问题