Check if string ends with certain pattern

后端 未结 5 1877
予麋鹿
予麋鹿 2020-12-03 00:11

If I have a string like:

This.is.a.great.place.too.work.

or:

This/is/a/great/place/too/work/

than my prog

5条回答
  •  孤城傲影
    2020-12-03 01:00

    This is really simple, the String object has an endsWith method.

    From your question it seems like you want either /, , or . as the delimiter set.

    So:

    String str = "This.is.a.great.place.to.work.";
    
    if (str.endsWith(".work.") || str.endsWith("/work/") || str.endsWith(",work,"))
         // ... 
    

    You can also do this with the matches method and a fairly simple regex:

    if (str.matches(".*([.,/])work\\1$"))
    

    Using the character class [.,/] specifying either a period, a slash, or a comma, and a backreference, \1 that matches whichever of the alternates were found, if any.

提交回复
热议问题