到目前为止,我正在尝试用 Java 开发一个简单的正则表达式,但没有成功。这是我想要完成的。
不接受空字符串。分隔数字的左侧或右侧至少需要一组数字。
13.
被接受;.13
也被接受。分隔符可能是
.
或,
。只允许出现一个或零个字符分隔符。
不允许单独使用不带数字的分隔符。例如,
.
不允许单独使用。
我面临的主要问题是如何使分隔符成为可选的。我正在尝试这个:
private final Pattern pattern = Pattern.compile("^[0-9]*.?|,?[0-9]*$");
在这里,我试图在字符串的开头指定一个数字列表,这些数字是可选的。稍后,我指定了一个分隔符,它可以是可选的,.
也可以,
是可选的。后来右边,也是一串数字,也是可选的。这是问题所在:只有一个.
或一个空字符串匹配。
这是我的代码:
Matcher matcher = clazz.pattern.matcher(input);// a empty string should not be matching
System.out.println(input+" "+matcher.matches());
input="a";
matcher = clazz.pattern.matcher(input);//true how can i fix this letter should not be allowed....
System.out.println(input+" "+matcher.matches());
input="13.";
matcher = clazz.pattern.matcher(input);//returns true is OK.
System.out.println(input+" "+matcher.matches());
input=".13";
matcher = clazz.pattern.matcher(input);//returning false why is this if . is a character separator allowed.
System.out.println(input+" "+matcher.matches());
input="13.,";
matcher = clazz.pattern.matcher(input);//false is OK only one separator might be specify.
System.out.println(input+" "+matcher.matches());
input=",.13";
matcher = clazz.pattern.matcher(input);//false is OK only one separator might be specify.
System.out.println(input+" "+matcher.matches());
input="13,";
matcher = clazz.pattern.matcher(input);//true is OK only one separator might be specify. , in this case
System.out.println(input+" "+matcher.matches());
input=",13";
matcher = clazz.pattern.matcher(input);
System.out.println(input+" "+matcher.matches());//true is ok the separator is , in this case
input="1131313133";
matcher = clazz.pattern.matcher(input);
System.out.println(input+" "+matcher.matches());//true only numbers
input="113.1313.133.13";
matcher = clazz.pattern.matcher(input);
System.out.println(input+" "+matcher.matches());//false is OK only one appeareance of the separator is allowed.
input="1131313133.132313";
matcher = clazz.pattern.matcher(input);
System.out.println(input+" "+matcher.matches());//false why is this... please help
input=".";
matcher = clazz.pattern.matcher(input);
System.out.println(input+" "+matcher.matches()); //true how can i fix this i need a left or right sequence of numbers.
input=".....";
matcher = clazz.pattern.matcher(input);
System.out.println(input+" "+matcher.matches());//false is OK
input=",,,,,,,";
matcher = clazz.pattern.matcher(input);
System.out.println(input+" "+matcher.matches());//false is OK