2

テキスト ファイルを解析し、コロンの後の URL である文字列を返すメソッドを作成しようとしています。テキスト ファイルは次のようになります (ボット用です)。

キーワード:url
キーワード,キーワード:url

したがって、各行はキーワードと URL、または複数のキーワードと URL で構成されます。

これを行う方法について誰かが私に少し指示を与えることができますか? ありがとうございました。

スキャナーを使用する必要があると思いますが、私と同じようなことをしたいと思っている人は見つかりませんでした。

ありがとうございました。

編集:以下の提案を使用した私の試み。うまくいきません。どんな助けでも大歓迎です。

    public static void main(String[] args) throws IOException {
    String sCurrentLine = "";
    String key = "hello";

    BufferedReader reader = new BufferedReader(
            new FileReader(("sites.txt")));
    Scanner s = new Scanner(sCurrentLine);
    while ((sCurrentLine = reader.readLine()) != null) {
        System.out.println(sCurrentLine);
        if(sCurrentLine.contains(key)){
            System.out.println(s.findInLine("http"));
        }
    }
}

出力:

    hello,there:http://www.facebook.com
null
whats,up:http:/google.com

sites.txt:

   hello,there:http://www.facebook.com
whats,up:http:/google.com
4

4 に答える 4

2

BufferedReaderあなたがやっているように、ファイルを行ごとに読む必要があります。正規表現を使用してファイルを解析することをお勧めします。

パターン

(?<=:)http://[^\\s]++

トリックを行います、このパターンは言います:

  • http://
  • 任意の数の非スペース文字 (複数) が続く[^\\s]++
  • コロンが前にある(?<=:)

Stringを使用してファイルをプロキシする簡単な例を次に示します。

public static void main(String[] args) throws Exception {
    final String file = "hello,there:http://www.facebook.com\n"
            + "whats,up:http://google.com";
    final Pattern pattern = Pattern.compile("(?<=:)http://[^\\s]++");
    final Matcher m = pattern.matcher("");
    try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(file.getBytes("UTF-8"))))) {
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            m.reset(line);
            while (m.find()) {
                System.out.println(m.group());
            }
        }
    }
}

出力:

http://www.facebook.com
http://google.com
于 2013-08-29T11:57:38.597 に答える
0

正規表現を使用できるテキスト解析には、BufferedReader を使用します。

于 2013-08-29T08:01:22.660 に答える
0

split メソッドを使用する必要があります。

String strCollection[] = yourScannedStr.Split(":", 2);
String extractedUrl = strCollection[1];
于 2013-08-29T08:28:31.837 に答える