final static private Pattern includePattern = Pattern.compile("^\\s+([^\\s]*)");
...
Matcher mtest = includePattern.matcher(" this.txt");
String ftest = mtest.group(1);
Run Code Online (Sandbox Code Playgroud)
我得到一个例外 No match found at java.util.regex.Matcher.group(Matcher.java:468)
我正在寻找至少1个空格字符,然后是一组捕获的非空格字符.我哪里出错了?
Bar*_*ers 12
您首先需要打电话.find()才能使用group(...).
注意find()返回a 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;
Run Code Online (Sandbox Code Playgroud)
并且[^\\s]可以改写为\\S(资本s).
你可能在你的问题中简化了你的例子,但我假设你知道String.trim()照顾任何前导和尾随空白字符的事实.