gpt4 book ai didi

java - 使用正则表达式检查字符串是否包含遵循格式的字符串

转载 作者:行者123 更新时间:2023-12-02 04:58:26 25 4
gpt4 key购买 nike

我想知道是否有人可以帮助我确定字符串是否包含某个正则表达式。

这是我到目前为止所拥有的:

Pattern pattern = Pattern.compile("\\[[0-9]+\\-+[0-9]\\]");
Matcher matcher = pattern.matcher(message);
System.out.println("" + matcher.matches());

如果消息类似于“[1-3]”,则返回 true,但如果消息周围有其他字符则返回 true。另外,我也希望能够获取字符串中的两个值。如有任何帮助,我们将不胜感激。

最佳答案

This [does not work] if it has other characters surrounding it.

这是因为 matches 会查找正则表达式来匹配整个字符串。如果您需要知道是否存在部分匹配,请改用 find():

System.out.println("" + matcher.find());

Also, I want to be able to get to the two values in the string too.

通过添加括号在数字部分周围创建捕获组:

Pattern pattern = Pattern.compile("\\[([0-9]+)\\-+([0-9])\\]");
Matcher matcher = pattern.matcher(message);
if (matcher.find()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}

请注意,第二个数字将是一位数字,除非您按照捕获第一个数字组的表达式中的方式在方括号后面添加 +

关于java - 使用正则表达式检查字符串是否包含遵循格式的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28534810/

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