我想在这些条件下检查字符串是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
答案 0 :(得分:10)
尝试使用此模式:
^(?=.*[?@$]).{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
答案 1 :(得分:4)
如果你的意思是'?'或(' @'和' $')使用此
(
(?=.*[\$?]) // Must contain either $ or ?
(?=.*[@?]) // Must contain either @ or ?
..b..$ // Third character should be b
)
一行
((?=.*[\$?])(?=.*[@?])..b..$)