2013-11-10 2 views
0

Я не могу сделать мой регулярных выражений шаблон, чтобы иметь возможность ввода десятичной или фракцииRegEx Decimal или фракция

это моя картина: \\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) 
+0

не '12/12' = 1? –

ответ

4

Как насчет \\d{1,5}([.]\\d{1,3}|(\\s\\d{1,5})?[/]\\d{1,3})?

Это будет принимать номера в формате

xxxxx 
xxxxx.yyy 
xxxxx_yyyyy/zzz //_ represents space 
xxxxx/zzz 

Test

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 
+0

Это сработало! спасибо – Criz

+0

@Criz проверить мою обновленную версию. Я исправил небольшие ошибки, которые позволяли регулярному выражению принимать только '1 /' или '/ 2' – Pshemo

+0

Я пробовал вашу обновленную версию, она не работает, она принимает только 5digits, она не принимает. или символ/ – Criz

Смежные вопросы