【问题标题】:Check if a string has a particular format?检查字符串是否具有特定格式?
【发布时间】:2014-06-03 07:02:07
【问题描述】:

我需要一个boolean 来检查给定的字符串是否遵循以下格式:

x.x.x1.2.3 ,其中 x 是单个数字

if string format == x.x.x then TRUE.
if string format != x.x.x then FALSE.

我怎样才能做到这一点?

【问题讨论】:

  • 是的,有简单的 Java 答案。查看正则表达式。
  • \\d\\.\\d\\.\\d\\.正则表达式会这样做..
  • 我不知道应该使用哪个。有什么建议么?它们似乎都有效,将检查数百个字符串。
  • @ThatGuy343 - 您应该提供更好的示例 I/O。从我在您的问题中可以看到,x 是一个数字,一个数字可以有多个数字。但是到目前为止提供的所有答案都只考虑一个数字作为一个数字。以后不应该因为你最后不清楚的事情而责备答案。

标签: java regex string format


【解决方案1】:

您可以尝试使用这个正则表达式

String x = "9.8.7";
boolean matches = x.matches("\\d\\.\\d\\.\\d"); // true

注意点.转义 \\.,因为它在regex 中具有特殊含义。

这里有一些输入/输出示例:

"99.8.7"   -> false
"9.9.7."   -> false
"9.97"     -> false

【讨论】:

  • 我找不到任何使用此方法的错误,当我允许时将标记为答案。
【解决方案2】:

您可以在 Java 中使用正则表达式检查,如下所示:

String testString = "1.2.3";
boolean isCorrectFormat = testString.matches("\\d\\.\\d\\.\\d");

样本测试:

还有一些输入/输出样本:

"11.22.33" -> false

"1.2.3."   -> false

"1.23"     -> false

"1.1.1"    -> True

【讨论】:

    【解决方案3】:

    尝试String#matches 与正则表达式\d\.\d\.\d

      String str="1.2.3";
      boolean isMatch=str.matches("\\d\\.\\d\\.\\d");
    

    【讨论】:

    • @ThatGuy343 它实际上没有 - 尝试 12345 它也会匹配。您需要转义点。
    • 也匹配 1a2b3 或 1,2,3
    • @BoristheSpider 是的,你是对的,没听懂。
    • @TheLostMind,谢谢。
    【解决方案4】:
    String testString = "1.2.3";
    boolean isCorrectFormat = testString.matches("\\d\\.\\d\\.\\d"); \\ You have to escape the "." 
    

    【讨论】:

    • 好像多了一个右括号。
    【解决方案5】:

    试试:

    public static void main(String[] args) {
        String x = "1.2.3";
        boolean hi = x.matches("[0-9].[0-9].[0-9]");
        //or x.matches("\\d{1,10}\\.\\d{1,10}\\.\\d{1,10}");
        //Where 1-> is the minimum digits and 10 is the maximum number of digits before .
    
        System.out.println(hi);
    }
    

    【讨论】:

    • 不,1) 你没有。 2) 点匹配 everything,因此您的模式匹配任意 5 个字符 String,只要 135 是数字。
    • @BoristheSpider:谢谢鲍里斯.. :)
    猜你喜欢
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多