In Perl/PHP regex is's possible to match a sequence and get an array with matched sequences:
preg_match('/20[0-1][0-9]/', $inputstring, $array_return); // PHP
I can't figure out开发者_开发知识库 how to do this in Java. match.group()
returns the whole string.
Is this impossible?
What you can do is something similar to the following:
Pattern p = Pattern.compile("\\w"); // Replace "\\w" with your pattern
String str = "Some String To Match";
Matcher m = p.matcher(str);
List<String> matches = new ArrayList<String>();
while(m.find()){
matches.add(m.group());
}
After this, matches
will contain every substring that matched the Pattern.
In this case, it is just every letter, excluding spaces.
If you want to turn a List<String>
into a String[]
just use:
String[] matchArr = matches.toArray(new String[matches.size()]);
If you only want to return part of the match, use capturing parentheses.
For example, to get only the year out of an MM/DD/YYYY date, the regex you want is
\d{2}/\d{2}/(\d{4})
I don't know the specifics of doing it in Java (you might need to escape some characters, for example), but just knowing that you should look for "capturing groups" should be of use.
精彩评论