2

我一直试图在句子中获取第一个位置名称。所需的位置名称将准确地从第一句的第二个大写字母开始,然后准确地在第一个点之前结束(。)

例子:

 It is located at Supreme Court. Follow by some other text. 
                  ^           ^

期望输出

最高法院

抱歉,我无法向您展示我目前掌握的一段代码。经过一个小时的尝试,我一无所获。

如果您在 Ruby 中显示代码示例,将不胜感激。

4

5 回答 5

4

这个正则表达式:

regexp = /^.*?[A-Z].*?([A-Z].*?)\./
match = regexp.match(subject)
if match
    match = match[1]
else
    match = ""
end

将产生:Supreme Court

我从匹配第一个大写字母的字符串的开头开始,而忽略其他所有内容。然后我匹配第二个大写并将结果保存到反向引用 1 直到第一个点。

于 2011-10-14T00:09:24.367 回答
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.">
于 2011-10-14T00:09:31.363 回答
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
于 2011-10-14T00:12:55.660 回答
0

试试这个:

s = 'It is located at Supreme Court. Follow by some other text.'
/[A-Z].+?([A-Z].*)\..+?/.match(s)[1]
于 2011-10-14T00:20:28.023 回答
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
于 2011-10-14T00:22:34.100 回答