模式匹配第一和第三个单词的每次出现(中间都有)

时间:2013-04-19 00:31:19

标签: java android regex pattern-matching

我正在尝试一种简单的正则表达式模式。

我有一个看起来像这样的文本文件:

  

Blah Blah Blah http://www.google.com。别的什么,等等等等   呸。 http://x.oddree.com/image1.jpg。还有一些文字......等等等等。   http://x.oddree.com/image2.jpg

我想要抓住的是任何以http开头且以jpg结尾的文字。不是整个网址。只有以.jpg结尾的那些。

换句话说,我希望我的输出为:

  

http://x.oddree.com/image1.jpg http://x.oddree.com/image2.jpg

我的正则表达式是:“\ b(http)。*(jpg)\ b”它似乎有效。但是当与模式匹配一​​起使用时,我最终会得到从第一次出现http到最后出现的jpg的所有内容。我知道我必须双重转义才能将\ b更改为\ b,但它仍无法按预期工作。

我一直在墙上撞了几个小时。 : - )

以下是代码段:

             if(file.exists())
             {
                 StringBuilder text = new StringBuilder();

                 try {
                     BufferedReader br = new BufferedReader(new FileReader(file));
                     String line;

                     while ((line = br.readLine()) != null) {
                         text.append(line);
                         text.append('n');
                     }
                 }
                 catch (IOException e) {
                     //TODO Write some error handling.
                 }

                 Pattern pattern = Pattern.compile(
                         "\\b(http).*(jpg)\\b"
                     );

                 Matcher matcher = pattern.matcher(text);
                 while (matcher.find()) {

                     result.add(matcher.group());
                 }

                 my_text.setText(result.toString());
             }

1 个答案:

答案 0 :(得分:0)

Matcher m = Pattern.compile("\\bhttp://\\S+?\\.jpg\\b").matcher(s);