我一直试图在句子中抓取第一个位置名称。所需的位置名称将从第一个句子的第二个大写开始,然后在第一个点之前精确结束(。)
示例:
It is located at Supreme Court. Follow by some other text.
^ ^
渴望出局
最高法院
抱歉,我无法向您展示我到目前为止所获得的一段代码。经过一个小时的尝试,我什么都没有具体。
如果您在Ruby中显示代码示例,将非常感谢。
答案 0 :(得分:4)
这个正则表达式:
regexp = /^.*?[A-Z].*?([A-Z].*?)\./
match = regexp.match(subject)
if match
match = match[1]
else
match = ""
end
将产生:Supreme Court
我从匹配第一个首都的字符串的开头开始,而忽略了其他所有的东西。然后我匹配第二个大写并将结果保存到反向引用1直到第一个点。
答案 1 :(得分:1)
这对我有用:
irb(main):001:0> location = "It is located at Supreme Court. Follow by some other text."
=> "It is located at Supreme Court. Follow by some other text."
irb(main):002:0> location.match(/[^A-Za-z][\bA-Z][\w\s]*\./)
=> #<MatchData "Supreme Court.">
答案 2 :(得分:1)
s = 'It is located at Supreme Court. Follow by some other text.'
m = s.match /[A-Z][^A-Z]+([A-Z][^\.]+)/
result = m[1] #Supreme Court
答案 3 :(得分:0)
试试这个:
s = 'It is located at Supreme Court. Follow by some other text.'
/[A-Z].+?([A-Z].*)\..+?/.match(s)[1]
答案 4 :(得分:0)
这假设字符串的开头没有空格,因此它会查找紧跟在空格之后的第一个大写字母并抓取任何内容直到它找到的第一个句点。
str = "It is located at Supreme Court. Follow by some other text."
m = str.match(/\s([A-Z].*?)\./)
location = m.nil? ? "" : m[1] #just in case there's no match
p location #=> Supreme Court