1

I want to get one String from a String composed of many lines

Example String:

Date: May 12, 20003
ID: 54076
Content: Test
filename: Testing.fileextension
folder: Test Folder
endDate: May 13, 2003

The output I want is "Testing.filextension" I tried a couple methods, but none return just the filename.

Method Attempt 1:

String[] files = example.substring(example.indexOf("filename: ")
for (String filename : files){
    System.out.printlin(filename);
}

Method Attempt 2 was to try to split on a newline, but right now it just returns all the lines. My main issue is that the .split method takes (String, int), however, I don't have the int.

String[] files = example.split("\\r?\\n");
for (String filename : files){
    System.out.println(filename)
}
3
  • 1
    You're aware that String's .split is overloaded? One takes just a string, the other takes a string and an int. Commented Mar 13, 2018 at 19:28
  • If the input string contains filename: do you expect the result after filename: ? Also, are there multiple filename: in your input? Commented Mar 13, 2018 at 19:29
  • Yes multiple filenames. Some end in .txt, others end in .csv. And yes I just want the result after. I don't care about the word "filename: " Commented Mar 13, 2018 at 19:31

7 Answers 7

3

What about using streams? You should consider filtering lines you cannot split, e.g. when the splitting character is missing.

So try this one:

Map<String, String> myMap = Arrays.stream(myString.split("\\r?\\n"))
            .map(string -> string.split(": "))
            .collect(Collectors.toMap(stringArray -> stringArray[0], 
                    stringArray -> stringArray[1]));

    System.out.println(myMap.get("filename"));
Sign up to request clarification or add additional context in comments.

Comments

1

Is there another limitation? If not just combine with an if:

String keyword = "filename: ";
String[] files = example.split("\\r?\\n");
for(String file : files) {
    if(file.startsWith(keyword)){
        System.out.println(file.substring(keyword.length()));
    }
}

Comments

0

You can filter it this way:

String[] files = example.split("\\r?\\n");
for (String filename : files){
    if (filename.startsWith("filename"))
        System.out.println(filename);
}

Comments

0

try this:

String searchStr = "filename:";
example.substring(example.indexOf(searchStr) + searchStr.length()).split("\n")[0].trim();

Though I would suggest you that to structure the input into a HashMap, which would be easier for later use.

Comments

0

use

String[] files = example.split("\\r?\\n");
for (String filename : files){
    if (filename.startsWith("filename"))
        System.out.println(filename);
}

and if you wan't filename without fileextension

String[] files = example.split("\\r?\\n");
for (String filename : files){
    if (filename.startsWith("filename"))
        System.out.println(filename.split(".")[0]);
}

Comments

0
/**
 * @Author Jack <J@ck>
 * https://stackoverflow.com/questions/49264343/java-get-substring-or-split-from-multiline-string
 */
public class StringFromStringComposedOfManyLines {
    public static void main(String[] args) {
        String manyLinesString =
                "Date: May 12, 20003\n" +
                        "ID: 54076\n" +
                        "Content: Test\n" +
                        "filename: Testing.fileextension\n" +
                        "folder: Test Folder\n" +
                        "endDate: May 13, 2003\n";
        System.out.println(manyLinesString);

        // Replace all \n \t \r occurrences to "" and gets one line string
        String inLineString = manyLinesString.replaceAll("\\n|\\t||\\r", "");
        System.out.println(inLineString);
    }
}

Out: Date: May 12, 20003ID: 54076Content: Testfilename: Testing.fileextensionfolder: Test FolderendDate: May 13, 2003

Comments

0

I'd suggest using regular expression and named group like this:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegExTest {

    public static void main(String[] args) {

        // Your example string
        String exampleStr = "Date: May 12, 20003\nID: 54076\nContent: Test\nfilename: Testing.fileextension\nfolder: Test Folder\nendDate: May 13, 2003.";

        /* create the regex:
         * you are providing a regex group named fname
         * This code assumes that the file name ends with a newline/eof.
         * the name of the group that will match the filename is "fname".
         * The brackets() indicate that this is a named group.
         */
        String regex = "filename:\\s*(?<fname>[^\\r\\n]+)";

        // create a pattern object by compiling the regex
        Pattern pattern = Pattern.compile(regex);

        // create a matcher object by applying the pattern on the example string:
        Matcher matcher = pattern.matcher(exampleStr);

        // if a match is found
        if (matcher.find()) {
            System.out.println("Found a match:");
            // output the content of the group that matched the filename:
            System.out.println(matcher.group("fname"));
        }
        else {
            System.out.println("No match found");
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.