简体   繁体   中英

How to check if the TextField contains only (DOT) character

How to check if the TextField contains only (DOT) character. The TextField can contain the following below things...

.9 = > Valid
9. = > Valid
9.23 = >Valid

But if the TextField contains only (.), then the user should be thrown an error message. I cannot do a Text.startsWith() or neither Text.contains() as both may fail in other cases.

Use this regular expression

text.matches("\\d+|\\d*\\.\\d+|\\d+\\.\\d*")
  • \\\\d+ matches only digits
  • \\\\d*\\\\.\\\\d+ matches strings that start either with dot or digit and contain a dot
  • \\\\d+\\\\.\\\\d* matches strings that start with digit, contain a dot and any number of digits after it

Keep in mind that numbers starting with 0 will also be accepted by this expression.

You can simply use

text.equals(".")

or, to take whitespaces into account,

text.trim().equals(".")

If you also have to check that in addition to the dot you also have a digit, you should probably write a couple of regexps.

In your case a string is valid if it matches the following patterns:

\d+       // Digits without the dot
\d*\.\d+  // Number with some digits after the dot
\d+\.\d*  // Number with some digits before the dot

you can just use two method

if(yourTextFieldName.getText().endsWith(".") && yourTExtFieldName.startsWith(".")) {
    //write your code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM