简体   繁体   中英

Java regex: Get the matched sequence

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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