繁体   English   中英

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

[英]what is wrong with this java regex?

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

...

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

我得到一个异常No match found at java.util.regex.Matcher.group(Matcher.java:468)

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

在使用group(...)之前,首先需要调用.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()处理任何前导和尾随空白字符的事实。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM