正则表达式-匹配句子中每个单词的除第一个字母外的所有字母 [英] Regular Expression - Match all but first letter in each word in sentence

查看:656
本文介绍了正则表达式-匹配句子中每个单词的除第一个字母外的所有字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎可以在这里找到答案,但是我想念一些东西,希望这里有人可以帮助我.

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.

我需要得到以下结果:

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?

谢谢.

推荐答案

尝试一下:

\B[a-z]

\B\b相反-它匹配没有单词边界的地方-当我们看到另一个字母之后的字母时.

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

您的正则表达式将整个单词的尾部-[a-z]+替换为一个星号.您应该一一替换它们.如果您希望它起作用,则应该匹配一个字母,但是check后面有一个单词(这毫无意义,因为您最好检查单个字母(?<=[A-Za-z])[a-z]):

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)

这篇关于正则表达式-匹配句子中每个单词的除第一个字母外的所有字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆