检查字符串是否以某种模式结束 [英] check if string ends with certain pattern
问题描述
如果我有一个字符串:
This.is.a.great.place.too.work.
或:
This/is/a/great/place/too/work/
比我的程序应该告诉我这句话是有效的并且它有工作。
than my program should give me that the sentence is valid and it has "work".
如果我有:
This.is.a.great.place.too.work.hahahha
或:
This/is/a/great/place/too/work/hahahah
然后我的程序不应该告诉我句子中有工作。
then my program should not give me that there is a "work" in the sentence.
所以我正在查看java字符串,以便在。或,或 / 在它之前。我怎样才能做到这一点?
So I am looking at java strings to find a word at the end of the sentance having ., or , or / before it. How can I achieve this?
推荐答案
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.
所以:
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$"))
使用字符类 [。,/ ]
指定一个句点,一个斜杠或一个逗号,以及一个反向引用, \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.
这篇关于检查字符串是否以某种模式结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!