简体   繁体   English

检查Java正则表达式中的特定字符

[英]Check specific character in Java Regex

How check if a String contains only one specific character? 如何检查一个字符串是否仅包含一个特定字符? Eg: 例如:

On the String square/retrofit and square/retrofit/issues I need to check if the String has more than one / character. 在String square/retrofitsquare/retrofit/issues我需要检查String是否具有多个/字符。

square/retrofit/issues need to be false because have more than one / character and square/retrofit need to be true. square/retrofit/issues必须为假,因为具有多个/字符, square/retrofit必须为真。

The string can have numbers. 字符串可以有数字。

You do not need regex. 您不需要正则表达式。 Simple indexOf and lastIndexOf methods should be enough. 简单的indexOflastIndexOf方法就足够了。

boolean onlyOne = s.indexOf('/') == s.lastIndexOf('/');

EDIT 1 编辑1
Of course, if / does not appear in given string above will be true . 当然,如果/不在给定字符串中,则为true So, to avoid this situation you can also check what is returned index from one of these methods. 因此,为避免这种情况,您还可以检查从这些方法之一返回的索引。

EDIT 2 编辑2
Working solution: 工作解决方案:

class Strings {
    public static boolean availableOnlyOnce(String source, char c) {
        if (source == null || source.isEmpty()) {
            return false;
        }

        int indexOf = source.indexOf(c);
        return (indexOf == source.lastIndexOf(c)) && indexOf != -1;
    }
}

Test cases: 测试用例:

System.out.println(Strings.availableOnlyOnce("path", '/'));
System.out.println(Strings.availableOnlyOnce("path/path1", '/'));
System.out.println(Strings.availableOnlyOnce("path/path1/path2", '/'));

Prints: 印刷品:

false
true
false

Or if you'd like to use a bit more modern approach with streams: 或者,如果您想对流使用更现代的方法:

boolean occursOnlyOnce(String stringToCheck, char charToMatch) {
    return stringToCheck.chars().filter(ch -> ch == charToMatch).count() == 1;
}

Disclaimer: This is not supposed to be the most optimal approach. 免责声明:这不应该是最好的方法。

A bit more optimized approach: 更优化的方法:

    boolean occursOnlyOnce(String stringToCheck, char charToMatch) {
    boolean isFound = false;
    for (char ch : stringToCheck.toCharArray()) {
        if (ch == charToMatch) {
            if (!isFound) {
                isFound = true;
            } else {
                return false; // More than once, return immediately
            }
        }
    }
    return isFound; // Not found
}

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

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