【问题标题】:Pattern match every occurence of first and third words (with everything inbetween)模式匹配第一个和第三个单词的每次出现(介于两者之间)
【发布时间】:2013-04-19 08:40:31
【问题描述】:

我正在尝试我认为是一个简单的正则表达式模式。

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

废话废话http://www.google.com。这里有别的东西,呜呜呜 呸。 http://x.oddree.com/image1.jpg。还有一些文字……等等。 http://x.oddree.com/image2.jpg

我想从中获取的是任何以 http 开头并以 jpg 结尾的文本。不是完整的网址。只有那些以 .jpg 结尾的。

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

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

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

为此,我已经把头撞在墙上好几个小时了。 :-)

这是一个代码sn-p:

             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());
             }

【问题讨论】:

    标签: java android regex pattern-matching


    【解决方案1】:

    试试

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

    【讨论】:

    • 成功了!所以它是带有双重转义的 \S 然后是 +?对于“通过”语法。这与标准的 RegEx 相去甚远。我将不得不阅读更多关于模式匹配的文档。 :-) 感谢您的快速回答!
    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    相关资源
    最近更新 更多