String camelCasePattern = "([a-z][A-Z0-9]+)+";
boolean val = "camelCase".matches(camelCasePattern);
System.out.println(val);
以上打印错误。我试图匹配一个以小写字母开头的camelCase模式。我试过调整一下,但没有运气。 camelCase的模式是错误的吗?
答案 0 :(得分:4)
我会选择:
String camelCasePattern = "([a-z]+[A-Z]+\\w+)+"; // 3rd edit, getting better
System.out.println("camelCaseCaseCCase5".matches(camelCasePattern));
<强>输出强>
true
您当前的Pattern
匹配一个小写,后跟多个大写/数字,多次匹配,这就是它返回false
的原因。
答案 1 :(得分:2)
匹配测试用例的最佳方法是:
String camelCasePattern = "^[a-z]+([A-Z][a-z0-9]+)+";
这将确保它以lowecase开头,然后具有一个大写字母的重复模式,后跟一些小写字符
匹配camelCaseTest
但不匹配camelCaseDOneWrong
答案 2 :(得分:2)
假设“驼峰案例词”的定义如下:
[A-Za-z]
。[a-z]
。[A-Z]
。以下经过测试的Java程序包含一个可能有用的完全注释的正则表达式:
// TEST.java 20140529_0900
import java.util.regex.*;
public class TEST {
public static void main(String[] args) {
String data = "This has one camelCase word."+
"This hasTwo camelCaseWords."+
"NON CamelCase withDigits123 words.";
Pattern re_camel_case_word = Pattern.compile(
" # Match one camelCase word.\n" +
" \\b # Anchor to word boundary. \n" +
" [a-z]+ # Begin with one or more lowercase alphas. \n" +
" (?: # One or more parts starting with uppercase. \n" +
" [A-Z] # At least one uppercase alpha \n" +
" [a-z]* # followed by zero or more lowercase alphas. \n" +
" )+ # One or more parts starting with uppercase. \n" +
" \\b # Anchor to word boundary.",
Pattern.COMMENTS);
Matcher matcher = re_camel_case_word.matcher(data);
while (matcher.find())
System.out.println(matcher.group(0));
}
}
请注意,使用此定义时,不允许使用数字和其他非alpha字符。需要修改模式以适应其他“驼峰案例”定义。
答案 3 :(得分:1)
我会去String camelCasePattern = "([a-z]+[a-zA-Z0-9]+)+";
答案 4 :(得分:0)
尝试([a-z]+)([A-Z][a-z]*)*
或([a-z]+)([A-Z][a-z]+)*
。
答案 5 :(得分:0)
^[a-z]+([A-Z][a-z0-9]+)*$
匹配: 小 小大 小大大 smallA1
不匹配: 小大 camelCaseDOneWrong camelCaseDWHDone