如何检查字符串是否只包含一个特定字符? 例如:
在字符串 square/retrofit
和 square/retrofit/issues
上,我需要检查字符串是否有多个 /
字符。
square/retrofit/issues
需要为 false,因为有多个 /
字符,并且 square/retrofit
需要为 true。
字符串可以包含数字。
最佳答案
您不需要正则表达式。简单的 indexOf
和 lastIndexOf
方法就足够了。
boolean onlyOne = s.indexOf('/') == s.lastIndexOf('/');
编辑1
当然,如果 /
没有出现在上面给定的字符串中,则为 true
。因此,为了避免这种情况,您还可以检查这些方法之一返回的索引是什么。
编辑2
工作解决方案:
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;
}
}
测试用例:
System.out.println(Strings.availableOnlyOnce("path", '/'));
System.out.println(Strings.availableOnlyOnce("path/path1", '/'));
System.out.println(Strings.availableOnlyOnce("path/path1/path2", '/'));
打印:
false
true
false
关于java - 检查 Java 正则表达式中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54391705/