Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select first letter of each word of a string using regex

I am trying to select the first letter of each word of a string using regex but I faced a problem. I was able to select the first letter of first word using

/^\w?/igm

how do i modify this to select first letter of each word of a string ?

For an example i have string : I love dogs. I want the code to select I, L and D.

like image 596
Sandesh Pandey Avatar asked Oct 21 '17 12:10

Sandesh Pandey


People also ask

How do you get the first letter of each word in a string?

To get the first letter of each word in a string: Call the split() method on the string to get an array containing the words in the string. Call the map() method to iterate over the array and return the first letter of each word. Join the array of first letters into a string, using the join() method.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What does \b mean in regex?

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

How do I find the first character in a regular expression?

Using the regular expressions.The matches() method of the String class accepts a regular expression and verifies it matches with the current String, if so, it returns true else, it returns false. The regular expression to match String which contains a digit as first character is “^[0-9]. *$”.


1 Answers

Use a word boundary:

\b(\w)

This will capture in group 1 the first letter of each word.

  1. \b is a word boundary, it's a zero-length assertion that makes sure we don't have a word character before.
  2. (\w) is a capture group ( ) that matches a word character \w.

So we are matching a word character (and save it in group 1) that is not preceeded by another word character (ie. The first character of a word)

like image 142
Toto Avatar answered Oct 05 '22 03:10

Toto