-2

for example I have

..

a paragraph

a paragraph

a paragraph

..

more paragraphs

how do I extract these 3 sentences between the two ".." into a string? The data is from a file.

well, I tried to search for "..", then extract the strings between the two. But it failed so I did not post any of my code...

Community
  • 1
  • 1
Gavin Z.
  • 423
  • 2
  • 6
  • 16

3 Answers3

1

If you are sure there are no more occurences of .. in your text, and your text is a String then this might be the easiest solution:

String result = text.substring(text.indexOf("..") + 2, text.lastIndexOf("..") - 2);

If there are more occurences of .., you could use regular expressions or a Scanner. Here's a solution using regular expressions.

Pattern pattern = Pattern.compile(".*?\\.\\.(.*?)\\.\\.", Pattern.DOTALL);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
    String result = matcher.group(1);
    // ...
}

This code assumes that the first .. starts a paragraph, the second .. ends a paragraph. The following characters are to be ignored until the next occurence of ...

steffen
  • 16,138
  • 4
  • 42
  • 81
0

Have the program search for the first "..", while loop it, save everything until it reaches the second "..".

safaiyeh
  • 1,655
  • 3
  • 16
  • 35
0

Is it possible for you to try to make the separators something unique to the text? If you have multiple occurrences of ".." in your text, how would you plan to specify which ".." you want to grab?

If you make it something unique to the text, you can use the String.split() method, which will take the token and split the string based on it, making it easy to grab the text between the tokens you specify.

Zoltorn
  • 171
  • 1
  • 2
  • 10
  • no there are lots of ".." in the text, and I'm just trying to get the idea how to extract the string because what I'm really doing is take the ".." (actually is a command like .ll, .bp) and use these command to format the string that I want to extract between this command and the next... – Gavin Z. Feb 02 '14 at 01:17
  • If I understand you correctly, you're saying that you just want to find the text between a certain command you're entering in? But that command can show up multiple times in your string and you want to be able to parse each series of text between all the commands? – Zoltorn Feb 02 '14 at 01:22
  • Please see this post about String.split. http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java This seperates a string based on a given token (ex. your command) and stores the lines between those tokens in an array – Zoltorn Feb 02 '14 at 01:35