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

非 Y 不嫁゛ 提交于 2019-12-21 20:03:36

问题


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.


回答1:


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)




回答2:


Try this possibly:

(\w{1})\w*



回答3:


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

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>


来源:https://stackoverflow.com/questions/4790375/regular-expression-match-all-but-first-letter-in-each-word-in-sentence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!