检查字符串是否包含至少两个不同的字符?

时间:2014-08-26 15:07:53

标签: java regex

我有一个给定的字符串,我需要检查这个字符串是否包含至少两个不同的聊天/数字/下划线

有效字符串:
" 12aab"
" _aaaaaaa"
" BBBC"

无效字符串:
""
"的 ______ "
" 333333333333"

提前致谢!

5 个答案:

答案 0 :(得分:1)

您可以使用以下正则表达式匹配字符串,这些字符串有两个不同的字母或数字或_符号,

^\w*?(\w)(?!\1|$)\w*$

DEMO

public static void main (String[] args) throws java.lang.Exception {
    System.out.println(isMatch("12aab", "^\\w*?(\\w)(?!\\1|$)\\w*$"));
    System.out.println(isMatch("_aaaaaaa", "^\\w*?(\\w)(?!\\1|$)\\w*$"));
    System.out.println(isMatch("bbbc", "^\\w*?(\\w)(?!\\1|$)\\w*$"));
    System.out.println(isMatch("3333", "^\\w*?(\\w)(?!\\1|$)\\w*$"));
    System.out.println(isMatch("a", "^\\w*?(\\w)(?!\\1|$)\\w*$"));
    System.out.println(isMatch("________", "^\\w*?(\\w)(?!\\1|$)\\w*$"));
}
private static boolean isMatch(String s, String pattern) {
    try {
        Pattern patt = Pattern.compile(pattern);
        Matcher matcher = patt.matcher(s);
        return matcher.matches();
    } catch (RuntimeException e) {
        return false;
    }  
}

<强>输出:

true
true
true
false
false
false

答案 1 :(得分:0)

如果位置非常不同,将很难使用正则表达式。

只需使用一套Character,如果套装的尺寸为2,则您确定

答案 2 :(得分:0)

试试这个

  public boolean valid(String s){ // valid if contains 2 different chars or more
    if(s == null || s.length() < 2 )
        return false;
    char c = s.charAt(0);
    int i = 1;
    int size = s.length();
    while(i < size && c == s.charAt(i))
        i ++;
    return i != size;
  }

答案 3 :(得分:0)

我会尝试前一个字母/数字/下划线,然后确保它不是原始的:

(\w).*(?=\w)(?!\1)

答案 4 :(得分:0)

您可以使用带有简单for循环的方法来检查您传递的Strings是否有效。

boolean isValid(String s){
    char a = s.charAt(0); //store the first char of the String
    for(int i = 1; i < s.length(); i++)
        if(s.charAt(i) != a) //compare against every other char
            return true; // if at least one match, String is valid
    return false; // String consists of the same character.

}

使用以下方法测试方法:

System.out.println(isValid("12aab"));
System.out.println(isValid("_aaaaaaa"));
System.out.println(isValid("bbbc"));
System.out.println(isValid("a"));
System.out.println(isValid("______"));
System.out.println(isValid("333333333333"));

将输出:

true
true
true
false
false
false

希望这有帮助