RegEx十进制或分数

时间:2013-11-10 19:02:01

标签: java regex

我无法使我的正则表达式模式能够输入小数或分数

这是我的模式:\\d{0,5}([./]\\d{0,3})?

我的目标输入是十进制(12345.123),分数(12345 12/12)

我也尝试过这种模式:\\d{0,5}([.]\\d{0,3})?|\\d{0,5}^\\s([/]\\d{0,3})?$但它不起作用..

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.text.DefaultFormatter;

public class Regex extends DefaultFormatter {

  /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Matcher matcher;

  public Regex(Pattern regex) {
    setOverwriteMode(false);
    matcher = regex.matcher(""); // create a Matcher for the regular expression
  }

  public Object stringToValue(String string) throws java.text.ParseException {
      if (string == null || string.trim().equals("")) return null;
    matcher.reset(string); // set 'string' as the matcher's input

    if (! matcher.matches()) // Does 'string' match the regular expression?
      throw new java.text.ParseException("does not match regex", 0);

    // If we get this far, then it did match.
    return super.stringToValue(string); // will honor the 'valueClass' property
  }
}

然后我将它用于JFormattedTextField

Pattern decFraction = Pattern.compile("\\d{1,5}([.]\\d{1,3}|(\\s\\d{1,5})?[/]\\d{1,3})?");
        Regex Format = new Regex(decFraction);
        Format.setAllowsInvalid(false);
JFormattedTextField Field = new JFormattedTextField(Format)

1 个答案:

答案 0 :(得分:4)

\\d{1,5}([.]\\d{1,3}|(\\s\\d{1,5})?[/]\\d{1,3})?

怎么样?

这将接受格式

的数字
xxxxx
xxxxx.yyy
xxxxx_yyyyy/zzz   //_ represents space
xxxxx/zzz

测试

String regex="\\d{1,5}([.]\\d{1,3}|(\\s\\d{1,5})?[/]\\d{1,3})?";

System.out.println("12345 12/12".matches(regex));   //OK
System.out.println("123/123".matches(regex));       //OK
System.out.println("123.123".matches(regex));       //OK
System.out.println("12345".matches(regex));         //OK
System.out.println("123 /123".matches(regex));      //fail
System.out.println("123 .123".matches(regex));      //fail
System.out.println("/123".matches(regex));          //fail
System.out.println("123/".matches(regex));          //fail
System.out.println("123.".matches(regex));          //fail
System.out.println(".123".matches(regex));          //fail