Sugan S
Sugan S

Reputation: 1778

Regex to check more than one condition in Android

I need to validate the EditText value using Regex. The condition:

  1. User can enter unsigned integer
  2. User can enter floating point value.

I have achieved this using two different Pattern but I have no idea to how to check both in single Regex.

I used this following Regex

public boolean validFloatForString(String value) {
        String decimalPattern = "([0-9]*)\\.([0-9]*)";
        String integerPattern = "([0-9]*)";
        boolean match = Pattern.matches(decimalPattern, value)
                || Pattern.matches(integerPattern, value);
        System.out.println(match); // if true then decimal else not
        return match;
    }

Upvotes: 0

Views: 921

Answers (3)

davide
davide

Reputation: 1948

Your pattern String decimalPattern = "([0-9]*)\\.([0-9]*)" will match ., while integerPattern will always match. That's because * means 0 or more. I would use something like

String pattern = "^([0-9]+(?:\\.[0-9]*)?)";

Which matches unsigned integer and floats.

Edit 1

To match also unsigned floats, beginning with .

String pattern = "\\b([0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)\\b";

I also substitute the ^, which means beginning of the string to match, with word boundary \\b.

Upvotes: 1

npinti
npinti

Reputation: 52185

You could use something like so: ^[0-9]+(\\.[0-9]+)?$.

The above will make sure that the string is made up from one or more digits which is optionally followed by a decimal point and one or more digits.

Upvotes: 0

JavaDM
JavaDM

Reputation: 851

If you are on Android you could use the embedded validator for this and e.g. set the InputType:

EditText text = new EditText(this);
text.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);

Upvotes: 0

Related Questions