正则表达式 - 匹配句子中每个单词中除第一个字母以外的所有字母
我几乎在这里得到了答案,但我遗漏了一些东西,我希望这里有人可以帮助我。
我需要一个正则表达式来匹配句子中每个单词中除第一个字母之外的所有字母。然后我需要用正确数量的星号替换匹配的字母。例如,如果我有以下句子:
There is an enormous apple tree in my backyard.
我需要得到这个结果:
T**** i* a* e******* a**** t*** i* m* b*******.
我已经设法想出一个几乎可以做到这一点的表达式:
(?<=(\b[A-Za-z]))([a-z]+)
使用上面的示例句子,该表达式给我:
T* i* a* e* a* t* i* m* b*.
How do I get the right number of星号?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
\B
与\b
相反 - 它匹配没有单词边界的地方 - 当我们看到一个字母在另一个字母后面时。您的正则表达式正在用单个星号替换单词的整个尾部 -
[az]+
。您应该将它们一一替换。如果你想让它工作,你应该匹配一个字母,但是检查后面有一个单词(这有点毫无意义,因为你不妨检查一个字母(?<=[A- Za-z])[az]
):(请注意,最后一个正则表达式具有可变长度的lookbehind,这在大多数正则表达式风格中都没有实现)
Try this:
\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]
):(note that the last regex has a variable length lookbehind, which isn't implemented in most regex flavors)
您可以尝试这样做,
除每个单词的第一个字母之外的所有字符替换
这会将
==Hello==World==
中 为==H****==W** **==
You can try this
this will replace all characters except for the first letter of every word
from this
==Hello==World==
into==H****==W****==
尝试这个可能:
Try this possibly:
这是一个老问题了。添加答案,因为其他人似乎没有完全或清楚地解决这个问题。处理这个问题的最简单的正则表达式是
/(\B[az])/g
。这将添加“g”作为全局标志,因此将在整个字符串中重复单个字符搜索。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.