Xara
Xara

Reputation: 9098

Obtaining a specific string from a line written in file

I have a file from which i read line by line and i have written a code for obtaining a certain portion of the string(from that line) which comes between two specific words eg

[abc] long time ago [cde]

Now i have written the following code for obtaining the string long time ago

if (line.contains("[abc]") && line.contains("[cde]")) {
    int b = line.indexOf("abc");
    int cc = line.indexOf("cde");
    String tk = line.substring(b + 4, cc);
    System.out.println(tk);
}

This code works fine but now the problem is that.i come across the following line

[abc] long time ago [cde]    [abc] Everyday is a new day [cde]

Now, just give me an idea how to obtain these two strings... because they come on a same line and my code just considers the first one...

Upvotes: 1

Views: 124

Answers (2)

aretai
aretai

Reputation: 1641

Use regular expressions of this link as they will match every occurrence of a given String.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

while (line.contains("[abc]") && line.contains("[cde]")) {
    int b = line.indexOf("abc");
    int cc = line.indexOf("cde");
    String tk = line.substring(b + 4, cc);
    System.out.println(tk);
    line = line.substring(cc + 4);
}

Upvotes: 3

Related Questions