Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression - Match all but first letter in each word in sentence

I've almost got the answer here, but I'm missing something and I hope someone here can help me out.

I need a regular expression that will match all but the first letter in each word in a sentence. Then I need to replace the matched letters with the correct number of asterisks. For example, if I have the following sentence:

There is an enormous apple tree in my backyard.

I need to get this result:

T**** i* a* e******* a**** t*** i* m* b*******.

I have managed to come up with an expression that almost does that:

(?<=(\b[A-Za-z]))([a-z]+)

Using the example sentence above, that expression gives me:

T* i* a* e* a* t* i* m* b*.

How do I get the right number of asterisks?

Thank you.

like image 255
mahdaeng Avatar asked Jan 25 '11 05:01

mahdaeng


People also ask

What is regex match all except a specific word?

Regex Match All Except a Specific Word, Character, or Pattern December 30, 2020 by Benjamin Regex is great for finding specific patterns, but can also be useful to match everything except an unwanted pattern. A regular expression that matches everything except a specific pattern or word makes use of a negative lookahead.

How do you match a regular expression that does not contain ignorethis?

For example, here’s an expression that will match any input that does not contain the text “ignoreThis”. /^(?!.*ignoreThis).*/ Note that you can replace the text ignoreThis above with just about any regular expression, including:

What is a regular expression in JavaScript?

A regular expression can be a single character, or a more complicated pattern. A regular expression helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern.

What is a negative look ahead in regex?

A regular expression that matches everything except a specific pattern or word makes use of a negative lookahead. Inside the negative lookahead, various unwanted words, characters, or regex patterns can be listed, separated by an OR character.


2 Answers

Try this:

\B[a-z]

\B is the opposite of \b - it matches where there is no word boundary - when we see a letter that is after another letter.

Your regex is replacing the whole tail of the word - [a-z]+, with a single asterisks. You should replace them one by one. If you want it to work, you should match a single letter, but check is has a word behind it (which is a little pointless, since you might as well check for a single letter (?<=[A-Za-z])[a-z]):

(?<=\b[A-Za-z]+)[a-z]

(note that the last regex has a variable length lookbehind, which isn't implemented in most regex flavors)

like image 88
Kobi Avatar answered Sep 30 '22 14:09

Kobi


you can try this

\B\w

this will replace all character except first letter ini words

from this ==Hello==World== into ==H****==W****==

like image 33
nulled Avatar answered Sep 30 '22 16:09

nulled