regular expression to match everything until the last occurrence of /

前端 未结 3 604
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 09:08

Using a regular expression (replaceregexp in Ant) how can I match (and then replace) everything from the start of a line, up to and including the last occurrence of a slash?

相关标签:
3条回答
  • 2020-11-30 09:35

    What you want to do is match greedily, the longest possible match of the pattern, it is default usually, but match till the last instance of '/'.

    That would be something like this:

     .*\/
    

    Explanation:

    . any character
    * any and all characters after that (greedy)
    \/ the slash escaped, this will stop at the **last** instance of '/'
    

    You can see it in action here: http://regex101.com/r/pI4lR5

    0 讨论(0)
  • 2020-11-30 09:49

    You can match this:

    .*\/
    

    and replace with your text.

    DEMO

    0 讨论(0)
  • 2020-11-30 09:52

    Option 1

    • Search: ^.*/
    • Replace: Empty string
    • Because the * quantifier is greedy, ^.*/ will match from the start of the line to the very last slash. So you can directly replace that with an empty string, and you are left with your desired text.

    Option 2

    • Search: ^.*/(.*)
    • Replace: Group 1 (typically, the syntax would be $1 or \1, not sure about Ant)
    • Again, ^.*/ matches to the last slash. You then capture the end of the line to Group 1 with (.*), and replace the whole match with Group 1.
    • In my view, there's no reason to choose this option, but it's good to understand it.
    0 讨论(0)
提交回复
热议问题