[英]Regex pattern to match these rules
我需要一個正則表達式來匹配以下規則。
1. Atleast 1 numerical character.
2. Atleast 1 of these (!, @, #, $, %, _) non-alphanumeric characters.
3. Uppercase alphabets.
4. Lowercase alphabets
我嘗試如下創建模式,但問題是任何字符都可以位於任何位置。 我有點卡在這里。
^[[A-Z]+[a-z]+[0-9]+[!@#\\$%_]+]$
這些應滿足上述每個條件。
1. [0-9]+
2. [!@#\\$_%]+
3. [A-Z]+
4. [a-z]+
但是我如何將它們分組在一起,以便它們可以以任何順序出現,但每個組至少出現一次。
解決方案:
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!@#$%_])[A-Za-z0-9!@#$%_]*$
您需要使用正向超前斷言來分別和獨立地檢查每個條件:
^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%_]).*$
將匹配包含至少每個這些字符之一的任何字符串(但也可以包含其他字符)。
前瞻實際上並沒有參與比賽(這就是為什么您可以將它們先后放置-它們都錨定在字符串的開頭)的原因,但是它們可以查看其中包含的正則表達式是否可以在當前位置進行匹配。
說明:
^ # Start of string.
(?= # Look ahead to see if it's possible to match...
.* # any string
[A-Z] # followed by one uppercase ASCII letter.
) # End of lookahead.
(?=.*[a-z]) # Same for lowercase ASCII letter
(?=.*[0-9]) # Same for ASCII digit
(?=.*[!@#$%_]) # Same for this list of "special" characters
.* # Now match any string.
$ # End of string.
最簡單的解決方案是不檢查單個正則表達式中的所有內容。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] ){
// String to be scanned to find the pattern.
String line = "S9s_3g90ae98iogw4i%%%%%%%!@!89fh#453&!";
if ( line.matches("\\d") // at least one digit
&& line.matches("[!@#\\\\$_%]") // at least one special character
&& line.matches("[a-z]") // at least one lowercase
&& line.matches("[A-Z]") // at least one uppercase
) {
System.out.println("Found value: ");
} else {
System.out.println("NO MATCH");
}
}
}
您可以使用圖靈完整的編程語言。 不要嘗試使用正則表達式解決所有問題(就我所愛的程度而言)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.