【问题标题】:How do I select a string that has a word begins with a capital letter with a regex?如何选择一个单词以带有正则表达式的大写字母开头的字符串?
【发布时间】:2016-10-15 06:48:16
【问题描述】:

假设我有一个这样的数组:

> names
=> ["John", "Van", "der", "and", "an", "the boys and John Smith"]

如何从该数组中选择 JohnVanthe boys and John Smith

我尝试了this regex,但它错过了最后一个字符串,这是最棘手的:

/^[A-Z]\w*/

什么是更完整的方法,它可以捕获其他情况,即大写单词出现在我可能丢失的字符串中间?

编辑 1

我希望它能够捕获的另一个字符串是:John Van der Lyn,其中有一个名字的名字和姓氏中有一个常用字母。

【问题讨论】:

  • 匹配所有带有大写单词的字符串还是只匹配大写名称?
  • @sagarpandya82 我会接受所有带有大写单词的字符串,因为我相信大写的名字是不可能的。但是,如果您有关于仅捕获大写名称的建议……请分享,因为这是最终目标。
  • ^(?=.*\b[A-Z]).*
  • @revo 这看起来是合法的。继续并将其添加为带有简短描述的答案,我会接受它。谢谢!
  • 如果您删除字符串开头的锚点 /[A-Z]\w*/,您的正则表达式会起作用

标签: ruby regex


【解决方案1】:

正则表达式:

^(?=.*\b[A-Z]).*

这得益于积极的前瞻性。它检查输入字符串中是否有任何以大写字母开头的单词然后匹配整个单词。

解释:

^               # Assert beginning of subject string
(?=             # Construct a positive lookahead
    .*\b[A-Z]       # Match start of a capitalized word
)               # End of lookahead
.*              # If lookahead was successful, match whole subject string

【讨论】:

    【解决方案2】:

    您可以使用简单的\b\p{Lu} 来查找任何以大写Unicode 字母开头的单词(因为\bword boundary):

    def get_names(names)
      names.select{ |name| name[/\b\p{Lu}/] }
    end
    
    names = ["John", "Van", "der", "and", "an", "the boys and John Smith"]
    puts get_names(names) # ['John', 'Van', 'the boys and John Smith']
    

    Ruby demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      相关资源
      最近更新 更多