You can use non-capturing groups, like this:
`Pattern pattern = Pattern.compile("(\\*)(?:\\S.*\\S)(\\*)");`
Basically, the match pattern contains 3 groups: (\\*), (?:\\S.*\\S), (\\*)
.
The second group is like (?:re), it is non-capturing group, means let regex don't count this group in the result.
Here is the sample code:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexTest {
/**
* @param args
*/
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(\\*)(?:\\S.*\\S)(\\*)");
String string ="for example *y text1 text2 u*";
Matcher matcher = pattern.matcher(string);
boolean found = false;
if (matcher.find()) {
System.out.println("group count:"+matcher.groupCount());
System.out.println("---------------");
for(int i=1; i<=matcher.groupCount(); i++)
{
System.out.println("group "+i);
System.out.println("start index:"+matcher.start(i));
System.out.println("end index:"+matcher.end(i));
System.out.println("text:"+string.substring(matcher.start(i), matcher.end(i)));
System.out.println("---------------");
}
found = true;
}
if(!found){
System.out.println("not found.");
}
}
}
Please note in java the group count in Matcher class is 1 based. The group count in the above code is 2.
If you don't use non-capturing group like this:
Pattern pattern = Pattern.compile("(\\*)(\\S.*\\S)(\\*)");
The result will return 3 groups.
For details, please refer this link:
http://java.sun.com/docs/books/tutorial/essential/regex/groups.html