gpt4 book ai didi

java - 这个java正则表达式有什么问题?

转载 作者:行者123 更新时间:2023-12-02 00:53:22 24 4
gpt4 key购买 nike

final static private Pattern includePattern = Pattern.compile("^\\s+([^\\s]*)");

...

Matcher mtest = includePattern.matcher(" this.txt");
String ftest = mtest.group(1);

我收到异常在 java.util.regex.Matcher.group(Matcher.java:468) 处找不到匹配项

我正在寻找至少 1 个空格字符,后跟一组捕获的非空格字符。我哪里出错了?

最佳答案

您首先需要调用.find(),然后才能使用group(...)

请注意,find() 返回一个 boolean 值,因此执行以下操作是安全的(r):

final static private Pattern includePattern = Pattern.compile("^\\s+([^\\s]*)");
Matcher mtest = includePattern.matcher(" this.txt");
String ftest = m.find() ? mtest.group(1) : null;

并且[^\\s]可以重写为\\S(大写s)。

您可能在问题中稍微简化了示例,但我假设您知道 String.trim() 会处理任何前导和尾随空白字符。

关于java - 这个java正则表达式有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3636674/

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