Java Regex 8数字+一个选项小数点,总共9个字符

时间:2021-05-16 17:06:54

I have a TextEdit field in my Android application. The pattern I need to match with this field is 0-8 digits and then an optional period and one decimal point. So 8 numbers + a decimal point for a total of 9 characters. The 9th digit can only be used if it follows the period.

我的Android应用程序中有一个TextEdit字段。我需要与此字段匹配的模式是0-8位数,然后是可选的句点和一个小数点。所以8个数字+一个小数点,总共9个字符。只有在句号之后才能使用第9位数字。

Example test cases that should pass: 1 12345678 12345678.9 12.3 .5

应通过的示例测试用例:1 12345678 12345678.9 12.3 .5

My code is as follows,

我的代码如下,


On my EditText

在我的EditText上

mFrequency = (EditText) v.findViewById(R.id.myField)
mFrequency.addTextChangedListener(mFrequencyEditTextListener);
InputFilter[] frequencyViewInputFilters = { new DecimalDigitsInputFilter()};
        mFrequency.addTextChangedListener(mFrequencyEditTextListener);


In my DecimalDigitsInputFilter Class

在我的DecimalDigitsInputFilter类中

public DecimalDigitsInputFilter()
   { 
      mPattern=Pattern.compile("\\d{0,8}(\\.|(\\\\.\\d))?");
   }


@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    Matcher matcher=mPattern.matcher(dest);
    if(!matcher.matches())
        return "";
    return null;
}

It passes all of my test cases, but fails the following: 123456789
It is allowing the user to enter 9 digits, without a period before the last digit.

它通过了我的所有测试用例,但未通过以下操作:123456789它允许用户输入9位数字,而不是最后一位数字之前的句点。

My previous Regex was \\d{0,8}(\\.|(\\.\\d))?
It allowed the user to enter 123456789 as well as 12345678.99

我之前的正则表达式是\\ d {0,8}(\\。|(\\。\\ d))?它允许用户输入123456789以及12345678.99


Any help would be greatly appreciated.

任何帮助将不胜感激。

1 个解决方案

#1


0  

This regex should work:

这个正则表达式应该工作:

\d{0,8}(?:\.\d)?

Explanation

\d{0,8} matches between 0 and 8 digits.

\ d {0,8}匹配0到8位数字。

(?:\.\d) matches a period followed by a digit.

(?:\。\ d)匹配句点后跟数字。

? makes the previous bit optional.

?使前一位可选。

#1


0  

This regex should work:

这个正则表达式应该工作:

\d{0,8}(?:\.\d)?

Explanation

\d{0,8} matches between 0 and 8 digits.

\ d {0,8}匹配0到8位数字。

(?:\.\d) matches a period followed by a digit.

(?:\。\ d)匹配句点后跟数字。

? makes the previous bit optional.

?使前一位可选。