我正在尝试从文本中获取大写单词。我如何为此使用 .match() ? 示例
text = "Pediatric stroke (PS) is a relatively rare disease, having an estimated incidence of 2.5–13/100,000/year [1–4], but remains one of the most common causes of death in childhood, with a mortality rate of 0.6/100,000 dead/year [5, 6]"
我需要类似的东西:
r = /[A-Z]/
puts r.match(text)
我从未使用过 match,我需要一种获取所有大写单词(缩写词)的方法。
最佳答案
如果您只想要首字母缩略词,则可以使用类似以下内容的内容:
text = "Pediatric stroke (PS) is a relatively rare disease, having an estimated incidence of 2.5–13/100,000/year [1–4], but remains one of the most common causes of death in childhood, with a mortality rate of 0.6/100,000 dead/year [5, 6]"
text.scan(/\b[A-Z]+\b/)
# => ["PS"]
匹配整个单词非常重要,这就是 \b
的用处,因为它标记了单词边界。
问题是当您的文本包含单个独立的大写字母时:
text = "Pediatric stroke (PS) I U.S.A"
text.scan(/\b[A-Z]+\b/)
# => ["PS", "I", "U", "S", "A"]
此时我们需要对正在搜索的文本内容有更多的情报和预知。问题是,单字母缩写词有效吗?如果没有,那么稍作修改就会有所帮助:
text.scan(/\b[A-Z]{2,}\b/)
# => ["PS"]
{2,}
在 the Regexp documentation 中进行了解释,因此请阅读该内容以获取更多信息。
i only want acronym type " (ACRONYM) ", in this case PS
通过你的描述很难看出你想要什么。缩写词定义为:
An acronym is an abbreviation used as a word which is formed from the initial components in a phrase or a word. Usually these components are individual letters (as in NATO or laser) or parts of words or names (as in Benelux).
根据Wikipedia 。根据该定义,小写、全部大写和混合大小写都可以有效。
如果,您的意思是您只想在括号内全部大写,那么您可以轻松修改正则表达式以实现这一点,但是您可能会遇到其他可能遇到的首字母缩略词,因为缺少您应该想要的首字母缩略词,或者通过捕获其他你应该忽略的。
text = "(PS) (CT/CAT scan)"
text.scan(/\([A-Z]+\)/) # => ["(PS)"]
text.scan(/\([A-Z]+\)/).map{ |s| s[1..-2] } # => ["PS"]
text.scan(/\(([A-Z]+)\)/) # => [["PS"]]
text.scan(/\(([A-Z]+)\)/).flatten # => ["PS"]
抓取文本的方式有多种,但这只会在您查看“List of medical abbreviations”和“Medical Acronyms / Abbreviations”时打开新的蠕虫 jar 。
通常,我会有一个我会接受的表格,使用一个简单的模式来捕获任何看起来像我想要的东西,检查它是否在表格中,然后保留它或拒绝它。如何做到这一点需要您自己弄清楚,因为这是一个完全不同的问题,不属于本问题。
关于ruby - 如何在 ruby 中使用 match?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34138979/