gpt4 book ai didi

java - 为什么这个模式匹配代码不起作用?

转载 作者:行者123 更新时间:2023-12-01 23:08:03 25 4
gpt4 key购买 nike

我正在尝试在 Java 中进行一些模式匹配:

Pattern p = Pattern.compile("(\\d+) (\\.+)");
Matcher m = p.matcher("5 soy milk");
String qty = m.group(1);
String name = m.group(2);

我想得到一个包含“5”的字符串和一个包含“ bean 浆”的字符串。但是,此模式匹配代码给了我一个 IllegalStateException。

最佳答案

在尝试获取组之前,您必须调用 matches()

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#matches()

public boolean matches()

Attempts to match the entire region against the pattern. If the match succeeds then more information can be obtained via the start, end, and group methods.

试试这个:

Pattern p = Pattern.compile("(\\d+) (\\.+)");
Matcher m = p.matcher("5 soy milk");

if (m.matches())
{
String qty = m.group(1);
String name = m.group(2);
}

关于java - 为什么这个模式匹配代码不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22471491/

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