Giovanni
Giovanni

Reputation: 580

Getting initials from input by user Java

I have the following code:

System.out.printf("Please enter your full name: ");
userFullName = KyBdIn.nextLine();

userFullName= userFullName.trim().replaceAll(" +", " ");
userFullName = userFullName.replaceAll("(?<=\\w)\\w+", ".");
userFullName = userFullName.trim().replaceAll(" +", "");

System.out.println(userFullName);

and I'm just wondering how it works exactly?

Is it that \w means white space and that the ? questions it?

Upvotes: 1

Views: 442

Answers (2)

Bohemian
Bohemian

Reputation: 424993

The method replaceAll() takes two parameters; the first is a regex (regular expression) as its search term and the second is the replacement expression (which may also contain certain regex references, but none are used here).

This line:

userFullName = userFullName.trim().replaceAll(" +", " ");

calls trim(), which removes leading and trailing "whitespace" characters, then calls replaceAll() to replace "one or more spaces" with a single space.

Because this line is repeated later, doing it twice adds no value - either could be removed with affecting the end result.

This line:

userFullName = userFullName.replaceAll("(?<=\\w)\\w+", ".");

replaces one or more word characters that are preceded by a word character with a dot. The breakdown of the regex (without java's escaping of backslashes - ie "\\" is a string with a single backslash) is:

  • \w means a "word character", which is any letter, digit or underscore character
  • \w+ means "one or more word characters" (the plus sign means one or more of the preceding expression)
  • (?<=\w) is a "look behind", which asserts that the preceding input is a "word character"

Together, the regex (?<=\w)\w+ effectively "all but the first character of any word"

Upvotes: 3

Frank Thomas
Frank Thomas

Reputation: 2514

the \w stuff is a regular expression used to filter out whitespace.

.Trim() removes whitespace on either end of the string

replaceAll(" +", " ") replaces double spaces with single spaces

replaceAll("(?<=\\w)\\w+", ".") replaces inner whitespace with periods. this one uses a 'look behind' operation. http://www.regular-expressions.info/lookaround.html

replaceAll(" +", "") removes any remaining spaces.

Upvotes: 0

Related Questions