Simple Regex: match everything until the last dot

前端 未结 3 2087
一生所求
一生所求 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

    This will do the trick

    (.*)\.
    

    Regex Demo

    The first captured group contains the name. You can access it as $1 or \1 as per your language

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-08 01:21

    Use lookahead to assert the last dot character:

    .*(?=\.)
    

    Live demo.

    0 讨论(0)
提交回复
热议问题