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.
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.
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.
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).
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]. *$”.
Use a word boundary:
\b(\w)
This will capture in group 1 the first letter of each word.
\b
is a word boundary, it's a zero-length assertion that makes sure we don't have a word character before.(\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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With