如何在带有两个冒号的字符串中的第一个冒号之后提取文本?

时间:2014-10-07 13:08:22

标签: ruby regex

我有一个字符串Test Data: Before the Data : "The War"。我需要在第一个冒号后提取字符串。所以输出应该是:

  

在数据之前:"战争"

8 个答案:

答案 0 :(得分:2)

正则表达式与Keep运算符匹配

您可以使用:

/:\s*\K.*/

\ K定义

\K运算符在Ruby中没有详细记录,但您可以在perlre中找到它。

  

这种结构有一种特殊形式,称为\ K,它使正则表达式引擎能够保持"保持"它在\ K之前匹配的所有内容,而不包括在$& 。这有效地提供了可变长度的后视。 ...由于各种原因\ K可能比等效(?< = ...)构造更有效,并且在您希望有效地删除字符串中的其他内容的情况下,它尤其有用。

实践例子

请考虑以下事项:

string = %q{Test Data: Before the Data : "The War"}.match(/:\s*\K.*/).to_s
#=> "Before the Data : \"The War\""

这将匹配第一个冒号后跟可选空格,将匹配丢弃到该点,然后将其余字符串捕获为MatchData。在MatchData对象上调用#to_s会将匹配作为String返回,以进行分配或输出。

答案 1 :(得分:2)

a = 'Test Data: Before the Data : "The War"'
p a[/: (.+)/, 1] #=> "Before the Data : \"The War\""

我不明白为什么这里的一些解决方案如此复杂,正则表达式应该非常简单:首先找到第一个冒号然后捕获它之后的所有内容。

答案 2 :(得分:2)

使用字符串方法

作为一个示例,String#partition方法将允许您将模式指定为字符串或正则表达式。因为你基本上只想使用冒号作为分隔符来丢弃字符串的前半部分,所以这将起作用:

string = %q{Test Data: Before the Data : "The War"}.partition(': ').pop
#=> "Before the Data : \"The War\""

字符串方法本身并不比RegexpMatchData方法更好或更差,但在一般情况下它们通常更快。更重要的是,#partition是查看问题的另一种方式,并为您提供了一组操作结果的不同方法。

答案 3 :(得分:1)

使用字符串[]运算符:

'Test Data: Before the Data : "The War"'[/[^:]*:(.*)/,1]
# => " Before the Data : \"The War\""

Doc是here

正则表达式捕获第一个冒号后的所有内容。为了更加安全,我使用了一个否定类来匹配冒号之前的冒号[^:]

答案 4 :(得分:0)

只需删除第一个:

之前的所有字符串
'Test Data: Before the Data : "The War" '.sub(/^[^:]*:/, "")
# => " Before the Data : \"The War\" "

如果您不想要前导空格,请尝试此操作。

'Test Data: Before the Data : "The War" '.sub(/^[^:]*:\s*/, "")
# => "Before the Data : \"The War\" "

答案 5 :(得分:0)

'Test Data: Before the Data : "The War"'
.split(": ", 2).last
#=> "Before the Data : \"The War\""

答案 6 :(得分:0)

试试这个:

a = 'Test Data: Before the Data : "The War"'.split(':',2)
print a[1..a.length]
#=> Before the Data : "The War"

String#split接受第二个参数,即限制。

答案 7 :(得分:-1)

开玩笑(解决方案根本不是基于正则表达式):

s='Test Data: Before the Data : "The War"'

s.split(':')[1..-1].join(':').strip
# => "Before the Data : \"The War\""
相关问题