[英]Check String whether it contains certain charecters Java Regular Expression
我想在以下情況下檢查字符串true或false:
1. the string must be 5 charecters long
2. 3rd charecter should be 'b'
3. the string must contain special charecter like '?' or '@' and '$'
我仍然不知道該怎么做:
System.out.println("//b//b//b?//b//b//b" ,"akb?g");//this is totally wrong though
嘗試使用以下模式:
^(?=.*[?@$]).{2}b.{2}$
這是顯示如何使用此模式的代碼段:
if ("invalid".matches("(?=.*[?@$]).{2}b.{2}")) {
System.out.println("invalid matches");
}
if ("12b?3".matches("(?=.*[?@$]).{2}b.{2}")) {
System.out.println("12b?3 matches");
}
這是該模式的簡要說明:
^ from the start of the string
(?=.*[?@$]) assert that we see a special character anywhere, at least once
.{2} then match any two characters
b match a 'b' for the 3rd character
.{2} then match any two characters again
$ end of string
如果你的意思是“?” 或('@'和'$')使用此
(
(?=.*[\$?]) // Must contain either $ or ?
(?=.*[@?]) // Must contain either @ or ?
..b..$ // Third character should be b
)
一條線
((?=.*[\$?])(?=.*[@?])..b..$)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.