[英]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.