简体   繁体   English

如何检查TextField是否仅包含(DOT)字符

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

How to check if the TextField contains only (DOT) character. 如何检查TextField是否仅包含(DOT)字符。 The TextField can contain the following below things... TextField可以包含以下内容:

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

But if the TextField contains only (.), then the user should be thrown an error message. 但是,如果TextField仅包含(。),则应该向用户抛出错误消息。 I cannot do a Text.startsWith() or neither Text.contains() as both may fail in other cases. 我无法执行Text.startsWith()或都不执行Text.contains()因为在其他情况下两者都可能失败。

Use this regular expression 使用此正则表达式

text.matches("\\d+|\\d*\\.\\d+|\\d+\\.\\d*")
  • \\\\d+ matches only digits \\\\d+仅匹配数字
  • \\\\d*\\\\.\\\\d+ matches strings that start either with dot or digit and contain a dot \\\\d*\\\\.\\\\d+匹配以点或数字开头并包含点的字符串
  • \\\\d+\\\\.\\\\d* matches strings that start with digit, contain a dot and any number of digits after it \\\\d+\\\\.\\\\d*匹配以数字开头,包含点和其后任意数量的数字的字符串

Keep in mind that numbers starting with 0 will also be accepted by this expression. 请记住,此表达式也将接受以0开头的数字。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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