简体   繁体   中英

Check String whether it contains certain charecters Java Regular Expression

I want to check a string true or false under these conditions:

1. the string must be 5 charecters long
2. 3rd charecter should be 'b'
3. the string must contain special charecter like '?' or '@' and '$'

I can't figure what to do still I've done:

System.out.println("//b//b//b?//b//b//b" ,"akb?g");//this is totally wrong though

Try using this pattern:

^(?=.*[?@$]).{2}b.{2}$

Here is a code snippet showing how you might use this pattern:

if ("invalid".matches("(?=.*[?@$]).{2}b.{2}")) {
    System.out.println("invalid matches");
}
if ("12b?3".matches("(?=.*[?@$]).{2}b.{2}")) {
    System.out.println("12b?3 matches");
}

Demo

Here is a brief explanation of the pattern:

^            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

If you meant '?' or ('@' and '$') use this

(
   (?=.*[\$?])      // Must contain either $ or ?
   (?=.*[@?])       // Must contain either @ or ?
    ..b..$          // Third character should be b
)

One line

((?=.*[\$?])(?=.*[@?])..b..$)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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