繁体   English   中英

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

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

我有以下要求,只有当给定的字符串以“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") || ...)

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

^.*Y$

为你的第一个模式。

顺便说一句,你可以使用一个正则表达式3:

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

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

.*(?:Y|YEARS|Years)$

你可以从头开始直接使用.Match匹配。所以你的失败了。

您可以简单地使用正则表达式模式:

if (Pattern.matches(".*(Y|YEARS|Years)$",text)) {/*do something*/}

/((?!0)\\d+|0)(.\\d+)?(?:years|year|y)/gi

https://regex101.com/r/gJ6xD2/2

var text = "1.6y   1.5years  1year 1.5h";
text.match(/((?!0)\d+|0)(\.\d+)?(?:years|year|y)/gi);

结果[“1.6y”,“1。5年”,“1年”]

(?=^(0\.\d+|[1-9](?:\d+)?(?:\.\d+)?)(?:(\s+)?[\/-](\s+)?(?:0\.\d+|[1-9](?:\d+)?(?:\.\d+)?))*(?:\s+)?(?:y(?:(ea)?rs|ears?)?|m(?:onths?)?)$).*

https://regex101.com/r/kL7rQ1/3

我唯一不确定“2.3 - 4 / 6.2 y”格式是否可以接受,所以我把它包括在内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM