【问题标题】:I need something to look at the characters in a string and accept the string if it only has the certain characters in Java [closed]我需要一些东西来查看字符串中的字符并接受该字符串,如果它只有 Java 中的某些字符 [关闭]
【发布时间】:2023-03-31 15:31:01
【问题描述】:

如果字符串中包含这些字符,则语句将返回 true。 “-1234567890”。如果字符串除了这些字符之外还有其他内容,则语句将返回 false。字符可以是任意顺序和任意数量,只要它包含这些字符即可。所以 String a = "12-3";将返回 true 但 String b = "1a3-";将返回错误。 ** 它也不能通过 for 循环。

【问题讨论】:

  • 了解正则表达式,它们将比您想象的更强大。

标签: java string character contains


【解决方案1】:

如果您的输入是一个名为 input 的字符串,您可以这样做

input.matches("^[0-9\\-]*$")

这回答了您的确切问题 - 但我支持该评论说明要了解更多有关正则表达式的信息,您会发现它比您想象的更有用。

【讨论】:

  • 这不起作用,它说 \- 是非法的转义字符。
  • 啊是的 - 它需要 \\-
  • 您不需要^ 和$ 锚点和matches()。此外,当 - 位于字符类的末尾时,您不需要转义它。所以,matches("[0-9-]*") 应该也能正常工作。或者,如果你想使用\d:[\\d-]*。
  • 如果排除^$,表达式是否也不会匹配以字母开头或以字母结尾的字符串? ^$ 的目的不就是确保整个字符串与模式匹配吗?
【解决方案2】:

我会说

String str;

str.matches("^[0-9-]*$")

【讨论】:

    【解决方案3】:

    首先,matches 已经有 ^ $ 字符,所以你不必输入这些字符。 \\d 表示 [0-9] 和 - 不是特殊字符,因此您不必输入 \\ 你应该 + 而不是 * 因为我假设你不想将空字符串匹配到你的正则表达式。

    所以你应该使用:

    s.matches("[\\d-]+");
    

    代码:

    String arr[] = {"1-23a456-", "a123","123-","-","1","123123fwdf234","123-3453",""};
    for (String string : arr) {
        System.out.println(string + "==>" + string.matches("[\\d-]+"));
    }
    

    输出:

    1-23a456-==>false
    a123==>false
    123-==>true
    -==>true
    1==>true
    123123fwdf234==>false
    123-3453==>true
    ==>false  \\ empty string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多