simulating a grep in Java (Windows)

时间:2016-08-31 17:18:00

标签: java regex windows-7

I have to look for a string "Languages: " with languages after it.

I could for instance look for "Languages: English, German" and "Languages: German, English" if there are only 2 languages. If there are 3 I would need to look for 6 different combinations. For 4 there would be 24 combinations. For 5 there would be 120, etc., which is unwieldly.

I would like to do something like

grep Languages | grep English | grep German | grep Italian | grep Danish | grep French (or whatever the languages I am looking for would be). I don't think we can use grep on windows. I could use a regular expression but I don't know how to create one that could list languages in any order.

Any suggestions on what to do? Let's say I have a List< String > languages with all the languages I want to look for.

1 个答案:

答案 0 :(得分:0)

Here’s an idea to get you started. Hope you can develop it.

    boolean english = false;
    boolean danish = false;
    boolean hopi = false;
    boolean mandarin = false;
    if (inputString.contains("Languages: ")) {
        if (inputString.contains("English")) {
            english = true;
        }
        if (inputString.contains("Danish")) {
            danish = true;
        }
        if (inputString.contains("Hopi")) {
            hopi = true;
        }
        if (inputString.contains("Mandarin")) {
            mandarin = true;
        }
        System.out.println("English? " + english + " Danish? " + danish + " Hopi? " + hopi + " Mandarin? " + mandarin);
    }

If there are more than three or five languages, you will probably want some abstraction over them, maybe a class or enum to represent the languages you support. An EnumSet might be convenient for representing which languages are in your string, ignoring the order?

By the way, you noticed that you don’t need regular expressions?

Edit: if you have a List<String> languageList, you may want to do like:

    Set<String> languagesInInput = new HashSet<>();
    for (String language : languageList) {
        if (inputString.contains(language)) {
            languagesInInput.add(language);
        }
    }