Regular expression. Match everything except the first letter in each word in a sentence

I almost got the answer here, but something is missing for me, and I hope someone here helps me.

I need a regular expression that matches all but the first letter in each word of the sentence. Then I need to replace the corresponding letters with the correct number of stars. 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 managed to find an expression that almost does this:

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

Using the above sample sentence, this expression gives me:

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

How do I get the right number of stars?

Thank.

+3
source share
4 answers

Try the following:

\B[a-z]

\B \B - , - , .

- [a-z]+, . . , , , ( , (?<=[A-Za-z])[a-z]):

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

( , lookbehind, regex)

+7

:

(\w{1})\w*
0

An example in ruby ​​with a regex /([\w])([\w]*)/:

#!/usr/bin/env ruby

s = "There is an enormous apple tree in my backyard."

puts s.scan(/([\w])([\w]*)/).map{ |x| x[0] + '*' * x[1].size + ' ' }.join
# => T**** i* a* e******* a**** t*** i* m* b*******

Or the version that ends .at the end:

puts s.scan(/([\w])([\w]*( |.))/).map{ 
  |x| x[0] + '*' * (x[1].size - 1) + x[2] 
}.join
# => T**** i* a* e******* a**** t*** i* m* b*******.
0
source

This is an old question. Adding an answer, as others do not seem to solve this problem completely or clearly. The simplest regular expression that processes this is /(\B[a-z])/g. This adds 'g' as a global flag, so a one-character search will be repeated throughout the line.

string = "There is an enormous apple tree in my backyard."
answer = string.replace(/\B[a-z]/g, "*");

string = "There is an enormous apple tree in my backyard."
$("#stringDiv").text(string);

answer = string.replace(/\B[a-z]/g, "*");
$("#answerDiv").text(answer);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="stringDiv"></div>
<div id="answerDiv"></div>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1787616/


All Articles