Reputation: 2368
Given the following Java codes:
String test = "'abc,ab,123',,,'123,aa,abc',,,";
Pattern p = Pattern.compile("('\\w\\S+\')");
Matcher m = p.matcher(test);
boolean s = m.matches();
System.out.println(s);
I want to extract all the content in ''
, for example I want 'abc,ab,123'
and '123,aa,abc'
. Why the outout is:
false
My regular expression is like: "find a '
,followed by a number or a letter, followed by several non-space characters,followed by another '
". It should have a match, what's wrong?
Upvotes: 0
Views: 69
Reputation: 37023
Matcher.matches
will try to check if regex can match entire string (see the documentation here). Since your regex expects '
at the end, but your string last character is ,
matches returns false.
If you want to print one or more part of string which matches your regex you need to use Matcher.find method first to let regex engine localize this matching substring. To get next matching substring you can call find
again from the same Matcher. To get all matching substrings call find
until it returns false
as response.
Try:
String test = "'abc,ab,123',,,'123,aa,abc',,,";
Pattern p = Pattern.compile("'[^']*'");//extract non overlapping string between single quotes
Matcher m = p.matcher(test);
while (m.find()) { //does the pattern exists in input (sub)string
System.out.println(m.group());//print string that matches pattern
}
Upvotes: 3