使用正则表达式检查java中的字符串是否有效

sta*_*k92 2 java regex

我有以下要求,只有当给定的字符串以"Y"或"Years"或"YEARS"结尾时,才需要做几件事.

我尝试使用像这样的正则表达式.

String text=1.5Y;
if(Pattern.matches("Y$",text) || Pattern.matches("YEARS$",text) || Pattern.matches("Years",text))
{
//do
}
Run Code Online (Sandbox Code Playgroud)

然而,这是失败的.

有人可以指出我出错的地方或建议我任何其他可行的方法.

编辑:

谢谢.这有帮助.

最后我用过了 "(?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;
Run Code Online (Sandbox Code Playgroud)

man*_*uti 5

你这里不需要正则表达式:

if(text.endsWith("Y") || ...)
Run Code Online (Sandbox Code Playgroud)