如果我有一个像这样的字符串:
This.is.a.great.place.too.work.
或者:
This/is/a/great/place/too/work/
我的程序应该告诉我这个句子是有效的并且它有“作用”。
如果我有:
This.is.a.great.place.too.work.hahahha
或者:
This/is/a/great/place/too/work/hahahah
那么我的程序不应该告诉我句子中有“作品”。
因此,我正在查看 java 字符串,以在句子末尾查找前面有 .
或 ,
或 /
的单词。我怎样才能实现这个目标?
最佳答案
这真的很简单,String
对象有一个 endsWith
方法。
从您的问题来看,您似乎想要 /
、、
或 .
作为分隔符集。
所以:
String str = "This.is.a.great.place.to.work.";
if (str.endsWith(".work.") || str.endsWith("/work/") || str.endsWith(",work,"))
// ...
您还可以使用 matches
来执行此操作方法和一个相当简单的正则表达式:
if (str.matches(".*([.,/])work\\1$"))
使用字符类 [.,/]
指定句点、斜杠或逗号,以及与替代项匹配的反向引用 \1
被发现(如果有的话)。
关于java - 检查字符串是否以某种模式结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58322861/