London
London

Reputation: 15274

match first character of every word

Assuming all my words are seperated by blank spaces i.e sample sentence:

the browser keeps sending requests to check

I should match tbksrtc, which is first letter of every word. Is this better to do with regex? rather than spliting it into array(using blank space).

If yes, how would one write that regex?

Upvotes: 1

Views: 1198

Answers (3)

Mik378
Mik378

Reputation: 22171

I think that for this simple case, the more readable way is effectively to split the string:

public String generateInitials (String original){
    String[] words= original.split(" ");
    return retrieveInitialsOfEachWord(words);
}

private String retrieveInitialsOfEachWord(String[] words){
    String initials = "";
    for(String word : words){
        initials += word.substring(0,1);
    }
    return initials;
}

Indeed, it is more these few lines are far easier to understand than decoding a regexp and guessing the writer intents.

If developer doesn't well reveal his intention through the method name, it may be difficult to decode the regexp as expected.

Anyway, using basic java syntax or involving regexp with Matcher is just a matter of taste.

Upvotes: 0

Joey
Joey

Reputation: 354406

You can use the following regex:

(?<=^|\s)\p{L}

which will match a letter if preceded either by whitespace or the start of the string. Don't forget to escape with abandon to actually force that regex into a Java string.

Quick PowerShell test:

PS> $s = 'the browser keeps sending requests to check'
PS> -join [regex]::Matches($s, '(?<=^|\s)\p{L}')
tbksrtc

Upvotes: 2

Reimeus
Reimeus

Reputation: 159754

You could match non-whitespaces:

String str = "the browser keeps sending requests to check";
Matcher m = Pattern.compile("(\\S)(\\S+)").matcher(str);
while (m.find()) {
    System.out.print(m.group(1));
}

Upvotes: 1

Related Questions