【问题标题】:Regex for specifying an empty string用于指定空字符串的正则表达式
【发布时间】:2011-03-11 00:25:13
【问题描述】:

我使用需要指定正则表达式的验证器。在针对空字符串进行验证的情况下,我不知道如何生成这样的正则表达式。我可以使用什么正则表达式来匹配空字符串?

【问题讨论】:

  • 我不明白为什么你需要一个正则表达式来检查这个。
  • prabha 在下面评论说验证器要求它是一个正则表达式 - 这应该从一开始就是问题的一部分,而不是评论!
  • 编辑问题以提及正则表达式要求。

标签: java regex string


【解决方案1】:

如果你必须在 Java 中使用正则表达式来检查空字符串,你可以简单地使用

testString.matches("")

请看示例:

 String testString = "";
 System.out.println(testString.matches(""));

或检查是否只有空格:

String testString = "  ";        
testString.trim().matches("");

但无论如何使用

testString.isEmpty();
testString.trim().isEmpty();

从性能角度来看应该更好。

   public static void main(String[] args) {

        String testString = "";

        long startTime = System.currentTimeMillis();
        for (int i =1; i <100000000; i++) {

            // 50% of testStrings are empty.
            if ((int)Math.round( Math.random()) == 0) {
                testString = "";
            } else {
                testString = "abcd";
            }

             if (!testString.isEmpty()){
                testString.matches("");
            }

        }
        long endTime = System.currentTimeMillis();


        System.out.println("Total testString.empty() execution time: " + (endTime-startTime) + "ms");


        startTime = System.currentTimeMillis();

        for (int i =1; i <100000000; i++) {
            // 50% of testStrings are empty.
            if ((int)Math.round( Math.random()) == 0) {
                testString = "";
            } else {
                testString = "abcd";
            }

            testString.matches("");


        }

        endTime = System.currentTimeMillis();

        System.out.println("Total testString.matches execution time: " + (endTime-startTime) + "ms");

    }

输出:

C:\Java\jdk1.8.0_221\bin\java.exe 
Total testString.empty() execution time: 11023ms
Total testString.matches execution time: 17831ms

【讨论】:

  • 那是编译器优化。为了避免这种情况并实际比较苹果和苹果,请在循环中打印每个结果并测量,isEmpty 只有 有点好。
  • @Anand Rockzz 好点,我用更现实的例子更新了代码。可能仍然不完全是苹果和苹果,但我看到性能提高了 50%。
【解决方案2】:

为了检查空字符串,我想不需要正则表达式本身...... u 可以直接查看字符串的长度..

在许多情况下,空字符串和 null 一起检查以获得额外的精度。

like String.length >0 && String != null

【讨论】:

    【解决方案3】:

    正则表达式 ^$ 仅匹配空字符串(即长度为 0 的字符串)。这里^$分别是字符串锚点的开始和结束。

    如果你需要检查一个字符串是否只包含空格,你可以使用^\s*$。请注意,\s 是空白字符类的简写。

    最后,在 Java 中,matches 尝试匹配 整个 字符串,因此您可以选择省略锚点。

    参考文献

    API 参考


    非正则表达式解决方案

    你也可以使用String.isEmpty()来检查一个字符串的长度是否为0。如果你想看看一个字符串是否只包含空白字符,那么你可以先trim()它然后然后检查如果是isEmpty()

    【讨论】:

    • 感谢您的信息。正则表达式解决方案有效:)。我使用了一个验证器,需要指定一个正则表达式。无论如何,非常感谢
    【解决方案4】:

    我不具体了解 Java,但 ^$ 通常可以工作(^ 仅匹配字符串的开头,$ 仅匹配结尾)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多