簡體   English   中英

如何查找字符串是否包含“僅”特殊字符在java中

[英]How to find if a string contains “ONLY” Special characters in java

假設我將String定義為:

String splChrs      = "/-@#$%^&_-+=()" ;

String inputString = getInputString();  //gets a String from end the user

我想檢查String“ inputString ”是否包含字符串“ splChrs ”中包含的特殊字符,即如果inputString只包含“ splChrs ”中包含的字符,我想將布爾標志設置為true

eg:  String inputString = "#######@";  //set boolean flag=true

如果布爾標志包含“ splChrs ”中不包含的任何字母,則將其設置為false

eg:  String inputString = "######abc"; //set boolean flag=false

您可以使用:

String splChrs = "-/@#$%^&_+=()" ;
boolean found = inputString.matches("[" + splChrs + "]+");

PS:我已經在splChrs變量中重新排列了你的字符,以確保連字符開始避免轉義。 我還從字符串的中間刪除了一個冗余的(並且有問題的)連字符,否則它將賦予字符類不同的含義(表示范圍)。

感謝@AlanMoore關於字符類中字符的說明:

^如果它首先列出; 如果它沒有列在第一位; [任何地方; 並且&如果緊接着另一個&

試試這個,

if(inputString.matches("[" + splChrs + "]+")){

// set bool to true
}else{

// set bool to false
}

不要發明自行車,因為所有這些任務對每個人來說都很常見。 我建議盡可能使用Apache Commons lib: http//commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#containsOnly%28java.lang。串,%20char []%29


containsOnly

public static boolean containsOnly(String str,char [] valid)

Checks if the String contains only certain characters.

A null String will return false. A null valid character array will return false. An empty String (length()=0) always returns true.

 StringUtils.containsOnly(null, *)       = false
 StringUtils.containsOnly(*, null)       = false
 StringUtils.containsOnly("", *)         = true
 StringUtils.containsOnly("ab", '')      = false
 StringUtils.containsOnly("abab", 'abc') = true
 StringUtils.containsOnly("ab1", 'abc')  = false
 StringUtils.containsOnly("abz", 'abc')  = false


Parameters:
    str - the String to check, may be null
    valid - an array of valid chars, may be null 
Returns:
    true if it only contains valid chars and is non-null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM