我正在使用此模式检查
public static final Pattern VALID_FIRST_CHARACTERS = Pattern.compile("^[\\ \\'\\-]");
public boolean isValidFirstChar(String name) {
if (VALID_FIRST_CHARACTERS.matcher(name).matches()) {
return true;
}
return false;
}
没有运气,有人能帮助我吗?
答案 0 :(得分:1)
你可以像这样改变它,它会起作用:
public static void main(String[] args) throws FileNotFoundException {
System.out.println(isValidFirstChar("-test"));
System.out.println(isValidFirstChar("\\test"));
System.out.println(isValidFirstChar("\'test"));
System.out.println(isValidFirstChar("test"));
}
public static final Pattern VALID_FIRST_CHARACTERS = Pattern.compile("^[\\\\ \\' \\-].*");
public static boolean isValidFirstChar(String name) {
if (VALID_FIRST_CHARACTERS.matcher(name).matches()) {
return true;
}
return false;
}
结果是:
true
true
true
false
你必须逃避\\
for java,而且还有正则表达式,这就是为什么你需要\\\\
这将成为\\
翻译为正则表达式时...
结尾处的.*
表示匹配后的任何内容......因此它以\ or ' or -
开头,后跟任何内容。