简体   繁体   English

如何使用大写字母替换大写字母后跟一段时间?

[英]How do I replace a capital letter followed by a period with the capital letter only?

Anytime a strings contains a capital letter followed by a period, I'd like to replace the capital letter and period with just the capital letter. 任何时候字符串都包含大写字母后跟一个句点,我想用大写字母替换大写字母和句号。

Today MR. Johnson walked to the mail box.
=> Today MR Johnson walked to the mail box.

William SR. won the race.
=> William SR won the race.

I tried to accomplish this using gsub : 我尝试使用gsub完成此任务:

MyText = "William SR. won the race."
MyText = MyText.gsub(/[A-Z]\./,**I DON'T KNOW WHAT TO PUT HERE**]

I can match the capital letter followed by the period, but I can't figure out how to replace my match with the capital letter that precedes the period. 我可以匹配大写字母后跟句点,但我无法弄清楚如何用句号之前的大写字母替换我的匹配。

另一种没有环视和使用捕获组的方法:

MyText = MyText.gsub(/([A-Z])\./,'\1')

You should use a positive look behind to match it and replace it with nothing. 您应该使用正面的外观来匹配它并将其替换为空。

MyText = "William SR. won the race."
MyText = MyText.gsub(/(?<=[A-Z])\./, '')

Here is an example of it on Rubular. 以下是Rubular的一个例子 You could just use gsub! 你可以使用gsub! if you know you want to do the replacement in place instead of making a copy. 如果你知道你想要进行替换而不是复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM