简体   繁体   English

Java正则表达式:获取匹配的序列

[英]Java regex: Get the matched sequence

In Perl/PHP regex is's possible to match a sequence and get an array with matched sequences: 在Perl / PHP中,正则表达式可以匹配序列并获得具有匹配序列的数组:

preg_match('/20[0-1][0-9]/', $inputstring, $array_return); // PHP

I can't figure out how to do this in Java. 我不知道如何在Java中执行此操作。 match.group() returns the whole string. match.group()返回整个字符串。

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. 此后, matches将包含与模式匹配的每个子字符串。

In this case, it is just every letter, excluding spaces. 在这种情况下,它只是每个字母,不包括空格。

If you want to turn a List<String> into a String[] just use: 如果要将List<String>转换为String[] ,请使用:

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 例如,要仅获取MM / DD / YYYY日期中的年份,则所需的正则表达式为

\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. 我不知道在Java中执行此操作的具体细节(例如,您可能需要转义一些字符),但只是知道应该寻找“捕获组”即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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