【问题标题】:how to find if a string contains numbers followed by a specific string如何查找字符串是否包含数字后跟特定字符串
【发布时间】:2013-07-27 12:33:46
【问题描述】:

我有一个这样的字符串:

String str = "Friday 1st August 2013"

我需要检查:如果字符串包含“任意数字”后跟“st”字符串,则打印“yes”,否则打印“no”。

我试过了:if ( str.matches(".*\\dst") ) 和 if ( str.matches(".*\\d.st") ),但它不起作用。

有什么帮助吗?

【问题讨论】:

    标签: java string parsing


    【解决方案1】:

    用途:

    if ( str.matches(".*\\dst.*") )
    

    String#matches() 匹配从字符串开头到结尾的正则表达式模式。锚点 ^ 和 $ 是隐含的。所以,你应该使用匹配完整字符串的模式。

    或者,使用Pattern、Matcher 和Matcher#find() 方法在字符串中的任意位置搜索特定模式:

    Matcher matcher = Pattern.compile("\\dst").matcher(str);
    if (matcher.find()) {
        // ok
    }
    

    【讨论】:

    • +1 但为什么要提到模式/查找?这不是必需的,它的代码更多且可读性更低。您对他的比赛为什么不起作用以及如何解决它的解释是真实和最佳的答案。
    • @Bohemian。它会增加 OP 知识 :) 我猜不会造成任何伤害。 ;)
    【解决方案2】:

    正则表达式可以用来匹配这样的模式。例如

     String str = "Friday 1st August 2013"
        Pattern pattern = Pattern.compile("[0-9]+st");
        Matcher matcher = pattern.matcher(str);
        if(mathcer.find())
          //yes
        else
         //no
    

    【讨论】:

      【解决方案3】:

      你可以使用这个正则表达式:

      .*?(\\d+)st.*
      

      * 之后的? 是必要的,因为* 是“贪婪的”(它将匹配整个字符串)。 *? 进行“非贪婪”匹配。此外,该数字可以有多个数字(例如“15st”)。

      【讨论】:

        猜你喜欢
        • 2010-11-16
        • 2014-01-08
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 2021-11-21
        • 1970-01-01
        • 1970-01-01
        • 2022-06-14
        相关资源
        最近更新 更多