【问题标题】:Trying to extract a substring from a buffered reader that reads between certain tags尝试从在某些标签之间读取的缓冲阅读器中提取子字符串
【发布时间】:2013-01-04 01:36:57
【问题描述】:

我正在使用 bufferedreader 提取 5 个网页,每个网页用空格分隔,我想使用一个子字符串来提取每个页面的 url、html、源和日期。但是我需要有关如何正确使用子字符串来实现这一点的指导,干杯。

public static List<WebPage> readRawTextFile(Context ctx, int resId) {   

    InputStream inputStream = ctx.getResources().openRawResource(
            R.raw.pages);

    InputStreamReader inputreader = new InputStreamReader(inputStream);
    BufferedReader buffreader = new BufferedReader(inputreader);
    String line;
    StringBuilder text = new StringBuilder();

    try {
        while ((line = buffreader.readLine()) != null) {


            if (line.length() == 0) {       
                // ignore for now 
                                //Will be used when blank line is encountered
            }

            if (line.length() != 0)  {
         //here I want the substring to pull out the correctStrings
                int sURL = line.indexOf("<!--");
                    int eURL = line.indexOf("-->");
                line.substring(sURL,eURL);
                **//Problem is here**
            }
        }
    } catch (IOException e) {
        return null;

    }
    return null;
}

【问题讨论】:

  • 我希望如何提取文本对于我要删除标签的地址来说是这样的:google.co.uk.html
  • 为什么要进行子串操作?只需使用 String.replace() 代替。

标签: java android bufferedreader


【解决方案1】:

我想你想要的是这样的,

public class Test {
   public static void main(String args[]) {
    String text = "<!--Address:google.co.uk.html-->";
    String converted1 = text.replaceAll("\\<!--", "");
    String converted2 = converted1.replaceAll("\\-->", "");
    System.out.println(converted2);
   }

}

结果展示:地址:google.co.uk.html

【讨论】:

  • 谢谢,我看看能不能调整一下,这样我就可以保存 5 个网址。
  • 当您使用ReplaceAll()。那为什么这两种转换。您可以使用regex 来实现相同的目的。无论如何 +1。
【解决方案2】:

在 catch 块中不要return null,使用printStackTrace();。它将帮助您找出是否有问题。

        String str1 = "<!--Address:google.co.uk.html-->";
        // Approach 1
        int st = str1.indexOf("<!--"); // gives index which starts from <
        int en = str1.indexOf("-->");  // gives index which starts from -
        str1 = str1.substring(st + 4, en);
        System.out.println(str1);

        // Approach 2
        String str2 = "<!--Address:google.co.uk.html-->";
        str2 = str2.replaceAll("[<>!-]", "");
        System.out.println( str2);

注意 $100: 请注意,在 replaceAll 中使用正则表达式将替换包含正则表达式参数的字符串中的所有内容。

【讨论】:

  • 谢谢,不过我需要能够从缓冲读取器中提取地址。所以它会遍历并找到文本文件中的每个地址,去掉标签并返回地址
  • @rob12243 我不明白。无论如何,您可以使用任何逻辑来实现您的目标。
猜你喜欢
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
  • 2015-08-30
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
相关资源
最近更新 更多