我有以下要求,其中仅当给定的字符串以“ 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;

最佳答案

matches方法尝试匹配完整输入,因此请使用:

^.*Y$


为您的第一个模式。

顺便说一句,您可以在所有3种情况下使用一个正则表达式:

if (text.matches( "(?i)^.*Y(ears)?$" ) ) {...}


(?i)会忽略大小写匹配。

10-01 03:23