-2

I have a class NumericTextField extends JTextField.It only allows inputs based on a regex.What i need it to do is to only allow doubles.Most inputs if not all will be like 1 or 1.25 or 30.35 and so on.So it needs to only allow digits and only one decimal point.Till now i used a regex that allows more then one dot. I tried a couple of regex like the following :

^\\d*(\\.\\d+)?$

\\d*(\\.)?\\d+

(?<=^| )\\d+(\\.\\d+)?(?=$| )|(?<=^| )\\.\\d+(?=$| )

[0-9]+(?:\\.[0-9]*)?

And many more.The problem is that it won't accept the dot(unless i copy-paste),it will only accept digits.I'm trying to input it via the > key,my keyboard doesn't have a numeric keypad.Could that be the issue ? if so,how can i make it so that it only accepts one dot,the one near the letters,the > one?

How can i fix this ?

Here is the class :

 @SuppressWarnings("serial")
 class NumericTextField extends JTextField {

@Override
protected Document createDefaultModel() {
    return new NumericDocument();
}

private static class NumericDocument extends PlainDocument {
    // The regular expression to match input against (zero or more digits)

    private final static Pattern DIGITS = Pattern.compile("-?\\d+(\\.\\d+)?");

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        // Only insert the text if it matches the regular expression
        if (str != null && DIGITS.matcher(str).matches()) {
            super.insertString(offs, str, a);
        }
    }
}
}
Sorin Grecu
  • 1,036
  • 11
  • 30
  • How about not using regex and do a test like the answer here: http://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-a-numeric-type-in-java – gtgaxiola Jan 07 '14 at 18:26

3 Answers3

1

^-?\d+(\.\d+)?$ will allow for 1 or 1.X+ if that's what you're going for.

tenub
  • 3,386
  • 1
  • 16
  • 25
0

Try this one:

str.matches("^-?\\d+(\\.\\d+)?$");

It worked in the example (reusing your code):

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

public class HelloWorld{
    private final static Pattern DIGITS = Pattern.compile("-?\\d+(\\.\\d+)?");

     public static void main(String []args){
        String str = "2.2";

        // Only insert the text if it matches the regular expression
        if (str != null && DIGITS.matcher(str).matches()) {
            System.out.println("passed");
        }else{
            System.out.println("refused");
        }
     }
}
Caio Oliveira
  • 1,243
  • 13
  • 22
0

Try,

(-|\\+)?[0-9]+(\\.[0-9]+)?

enter image description here

String pattern = "(-|\\+)?[0-9]+(\\.[0-9]+)?";
String string = "2.2";
System.out.println(string.matches(pattern));

it prints true

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
  • Prints true as well.Added that to a new project to be all clean and stuff,still won't let me input `.` by keyboard.Weird – Sorin Grecu Jan 07 '14 at 19:28