简体   繁体   English

检查String是否包含某些字符Java正则表达式

[英]Check String whether it contains certain charecters Java Regular Expression

I want to check a string true or false under these conditions: 我想在以下情况下检查字符串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 '$'

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..$)

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

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