Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string ends in is valid or not in java using regex

Tags:

java

regex

I have the following requirement where in I need to do few things only if the given string ends in "Y" or "Years" or "YEARS".

I tried doing it using regex like this.

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

However this is getting failed.

Can someone point me where I have gone wrong or suggest me any other feasible method.

EDIT:

Thanks.That helps.

Finally I have used "(?i)^.*Y(ears)?$| (?i)^.*M(onths)?$".

But I want to make more changes to make it perfect.

Let's say I have many strings.

Ideally only strings like 1.5Y or 0.5-3.5Y or 2.5/2.5-4.5Y should pass if check.

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;
like image 760
starkk92 Avatar asked Apr 16 '26 22:04

starkk92


1 Answers

You don't need a regex here:

if(text.endsWith("Y") || ...)
like image 149
M A Avatar answered Apr 18 '26 11:04

M A