Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is wrong with this java regex?

Tags:

java

regex

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

...

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

I get an exception No match found at java.util.regex.Matcher.group(Matcher.java:468)

I'm looking for at least 1 space character followed by a captured group of nonspace characters. Where have I gone wrong?

like image 529
Jason S Avatar asked Sep 02 '26 11:09

Jason S


1 Answers

You'll first need to call .find() before you can use group(...).

Note that find() returns a boolean, so it's safe(r) to do something like this:

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

And [^\\s] could be rewritten as \\S (capital s).

You might have simplified your example a bit in your question, but I assume you're aware of the fact that String.trim() takes care of any leading and trailing white space characters.

like image 96
Bart Kiers Avatar answered Sep 04 '26 01:09

Bart Kiers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!