简体   繁体   中英

Regex stop after last slash

I'm very new to regex and I am trying to figure out this:

/games/athem
/games/athem/countdown

I want to get the whole line until the last /

So /games/athem should be valid but not /games/athem/countdown

(.*)$

This gives me everything, but I want to stop at the / . Also, how do I make sure it only works on /games/ and not, for example, /companies/athem ?

How would I do this? I tried searching but couldnt find something. Its just really confusing

You may use

^/games/[^/]+$

See the regex demo .

In Java, omit the anchors when using the pattern with the matches() method:

s.matches("/games/[^/]+")

Note you do not need to escape a / in a string pattern since / is not a special regex metacharacter and Java regex does not use regex delimiters.

Pattern details

  • ^ - start of string (implicit in matches() )
  • /games/ - a literal /games/ substring
  • [^/]+ - 1 or more chars other than /
  • $ - end of string (implicit in matches() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM