1

I have a txt file that includes :

Hello Word
myStrings = [str1, str2, str3]
Goodbye Word

I would like to read the file to find the "myStrings" string then have a loop to check if one of the myStrings value [str1, str2, str3] match with a some variable.

Currently I am finding the myStrings like this:

Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
    String fileline = scanner.nextLine();
    String myStringsKey = "myStrings =";
    if(fileline.startsWith(myStringsKey)) { 

    }
}

How can I achieve str2 for instance to check with a defined var? I assume I should use "split".

0

5 Answers 5

1

For parsing your string you can use the following simple method:

public String[] parseMyStrings(String s) {
    int beginIndex = s.indexOf("[") + 1;
    int endIndex = s.indexOf("]");

    s = s.substring(beginIndex, endIndex);

    // split and trim in one shot
    return s.split(("\\s*,\\s*"));
}

Then, your final code can look like this:

Scanner scanner = new Scanner(fileName);
while (scanner.hasNextLine()) {
    String fileline = scanner.nextLine();
    String myStringsKey = "myStrings =";
    if(fileline.startsWith(myStringsKey)) {

        String[] values = parseMyStrings(fileline);
        System.out.println(Arrays.toString(values));

    }
}

I think your code will be more readable and easier to extend or modify if you put the parsing logic into a separate method.

Sign up to request clarification or add additional context in comments.

Comments

1

You can make use of a regex and include it within the if block:

if (fileline.startsWith(myStringsKey)) {
    // regex to extract text within brackets
    Pattern p = Pattern.compile("(?<=\\[).+?(?=\\])");  
    Matcher m = p.matcher(fileline);

    while (m.find()) {
        System.out.println(m.group().split(",")[1]); // str2
    }
} 

5 Comments

but i need to check if a defined var equals str1 or str2 do we have a way to define dynamically instead of sayin [1]?
What this will return ? With which string it will compare ?Lets say this is a string "myStrings = [[st[r1, str2, str3]" and i want str3 as a output
I meant for instance i have defined static var myStatic="str3" and i have returned str1, str2, str3 between [ - ] these chars with your way. Comparison ill do between myStatic and the all other 3 strings. if i give [1] as u did ill get only str2 but i wanna find str3 or str1 according to defined one. - and in my project defined var will be dynamic ill get from user for instance.
You can loop through the array rather than accessing the index directly and then check - is that what you need?
@Mak: Once the line is split you can loop through it and check. Is that your downvote btw?
0

You have to parse the line's contents: You should first tear out the brackets, and then split the string by commas and add every item to a Set, which will contain the different values.

Then, checking if that set contains your desired value is immediate.

Comments

0

In a very simple way,

 Scanner scanner = new Scanner(fileName);
    while (scanner.hasNextLine()) {
        String fileline = scanner.nextLine();
        String myStringsKey = "myStrings =";
        if(fileline.startsWith(myStringsKey)) { 
            String[] temp = fileline.replaceAll("myStrings =","").replaceAll("\\[", "").replaceAll("\\]", "").trim().split(",");
                for (int i = 0; i < temp.length; i++) {
                    if(temp[i].trim().equalsIgnoreCase("str2")){
                        System.out.println("Str2 matched");
                    }
                }
        }
    }

2 Comments

This would fail if the strings include a bracket because it will replace the brackets within each string as well. For eg: ["ab[b", "zx[ccc"]
There are several ways to prevent them to replace such as fileline.replaceFirst("\[", "") or substring excluding first and last char, I just show him the way to do.
0
scanner = new Scanner(new File(fileName));
while (scanner.hasNextLine()) {
   String fileline = scanner.nextLine();
   if(fileline.contains("myStrings")) {
      String string = fileline.substring(fileline.indexOf("[") + 1, fileline.indexOf("]"));
      String[] vars = string.split(",");
      System.out.println(Arrays.toString(vars));
   }
}

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.