我有以下要求,仅当给定字符串以“Y”或“Years”或“YEARS”结尾时,我才需要做一些事情。
我尝试使用像这样的正则表达式来做到这一点。
String text=1.5Y;
if(Pattern.matches("Y$",text) || Pattern.matches("YEARS$",text) || Pattern.matches("Years",text))
{
//do
}
但是这失败了。
有人可以指出我哪里出错了,或者建议我任何其他可行的方法。
编辑:
谢谢。这有帮助。
最后我用了“(?i)^.*Y(ears)?$| (?i)^.*M(onths)?$”。
但我想做出更多改变以使其更加完美。
假设我有很多字符串。
理想情况下,只有 1.5Y 或 0.5-3.5Y 或 2.5/2.5-4.5Y 这样的字符串才能通过检查。
It can be number of years(Ex:2.5y) or the period of years(2.5-3.5y) or the no of years/period of years(Ex.2.5/3.5-4.5Y) nothing more.
More Examples:
--------------
Y -should fail;
MY - should fail;
1.5CY - should fail;
1.5Y-2.5Y should fail;
1.5-2.5Y should pass;
1.5Y/2.5-3.5Y should fail;
1.5/2.5-3.5Y should pass;
最佳答案
这里不需要正则表达式:
if(text.endsWith("Y") || ...)
关于java - 使用正则表达式检查java中以结尾的字符串是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30751885/