简体   繁体   English

检索正则表达式匹配的模式

[英]Retrieving Regex matched pattern

I need to retrieve a regex pattern matched strings from the given input. 我需要从给定的输入中检索正则表达式模式匹配的字符串。

Lets say, the pattern I need to get is like, 可以说,我需要得到的模式是

"http://mysite.com/<somerandomvalues>/images/<againsomerandomvalues>.jpg"

Now I created the following regex pattern for this, 现在,我为此创建了以下正则表达式模式,

http:\/\/.*\.mysite\.com\/.*\/images\/.*\.jpg

Can anybody illustrate how to retrieve all the matched pattern with this regx expression using Java? 谁能说明如何使用Java使用此regx表达式检索所有匹配的模式?

Some simple Java example: 一些简单的Java示例:

String my_regex = "http://.*.mysite.com/.*/images/.*.jpg";
Pattern pattern = Pattern.compile(my_regex);
Matcher matcher = pattern.matcher(string_to_be_matched);
// Check all occurance
while (matcher.find()) {
    System.out.print("Start index: " + matcher.start());
    System.out.print(" End index: " + matcher.end() + " ");
    System.out.println(matcher.group());
}

You don't mask slashes but literal dots: 您无需掩盖斜线,但可以掩盖文字点:

    String regex = "http://(.*)\\.mysite\\.com/(.*)/images/(.*)\\.jpg";
    String   url = "http://www.mysite.com/work/images/cat.jpg";
    Pattern pattern = Pattern.compile (regex);
    Matcher matcher = pattern.matcher (url);

    if (matcher.matches ())
    {
        int n = matcher.groupCount ();
        for (int i = 0; i <= n; ++i)
            System.out.println (matcher.group (i));
    }

Result: 结果:

www
work
cat

In fact, it is not clear if you want the whole matching string or only the groups. 实际上,不清楚是要整个匹配字符串还是仅需要组。

Bogdan Emil Mariesan's answer can be reduced to Bogdan Emil Mariesan的答案可以简化为

if ( matcher.matches () ) System.out.println(string_to_be_matched);

because you know it is mathed and there are no groups. 因为您知道它是数学运算,并且没有组。

IMHO, user unknown's answer is correct if you want to get matched groups. 恕我直言,如果您想获得匹配的组,则未知用户的答案是正确的。

I just want to add additional information (for others) that if you need matched group you can use replaceFirst() method too: 我只想添加其他信息(其他信息),如果您需要匹配的组,也可以使用replaceFirst()方法:

String firstGroup = string.replaceFirst( "http://mysite.com/(.*)/images/", "$1" );

But performance of Pattern.compile approach if better if there are two or more groups or if you need to do that multiple times (on the other hand in programming contests, for example, it is faster to write replaceFirst() ). 但是 ,如果有两个或多个组,或者如果您需要多次执行,则Pattern.compile方法的性能会更好(例如,在编程竞赛中,编写replaceFirst()更快)。

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

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