[ACCEPTED]-Regex to get first two words of unknown length from a string-regex

Accepted answer
Score: 13

If you have only spaces between words, split 3 by \\s+. When you split, the array would be 2 the words themselves. First two would be 1 in arr[0] and arr[1] if you do:

String[] arr = origString.split("\\s+");
Score: 6

With regular expressions you can do something 3 like this:

    public static ArrayList<String> split2(String line, int n){
    line+=" ";
    Pattern pattern = Pattern.compile("\\w*\\s");
    Matcher matcher = pattern.matcher(line);
    ArrayList<String> list = new ArrayList<String>();
    int i = 0;
    while (matcher.find()){
        if(i!=n)
            list.add(matcher.group());
        else
            break;
        i++;
    }
    return list;
}

if you want the first n words, or 2 simply this:

    public static String split3(String line){
    line+=" ";
    Pattern pattern = Pattern.compile("\\w*\\s\\w*\\s");
    Matcher matcher = pattern.matcher(line);
    matcher.find();
    return matcher.group();
}

if you want only the first and 1 second words.

Score: 5

If you want to split it on exactly the space 5 character:

String[] parts = args[i].split(" ");

If you want to split it on any 4 whitespace character (space, tab, newline, cr):

String[] parts = args[i].split("\\s");

To 3 treat multiple adjacent spaces as one separator:

String[] parts = args[i].split(" +");

Same 2 for whitespace:

String[] parts = args[i].split("\\s+");

The first two words would 1 be parts[0] and parts[1]

Score: 4

Assuming your "words" consist of alphanumeric 2 characters, the following regex will match 1 the first 2 words:

\w+\s+\w+
Score: 0

Use below method.

public static String firstLettersOfWord(String word) {
    StringBuilder result = new StringBuilder();
    String[] myName = word.split("\\s+");

    for (String s : myName) {
        result.append(s.charAt(0));
    }
    return result.toString();
}}

0

More Related questions