gpt4 book ai didi

java - 如何查找字符串是否包含数字后跟特定字符串

转载 作者:搜寻专家 更新时间:2023-11-01 01:22:00 24 4
gpt4 key购买 nike

我有这样一个字符串:

String str = "Friday 1st August 2013"

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

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

有什么帮助吗?

最佳答案

使用:

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

String#matches()从字符串的开头到结尾匹配正则表达式模式。 anchor ^$ 是隐式的。因此,您应该使用匹配完整字符串的模式。

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

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

关于java - 如何查找字符串是否包含数字后跟特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17897864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com