2014-12-04 20 views
0

我有一个字符串,它是这样的:这段代码对'match'和regex有什么问题?

ABC:Something|Hello World 

我想以后的数据“|”字符,所以我使用它的正则表达式。

sample_str = "ABC:Something|Hello World" 
puts sample_str.match(/[^|]*$/) 

这适用于rubular,并返回我“Hello World”作为输出,但不能在我的ruby代码中工作。我在这里错过了什么?我在Ruby中获得#<MatchData "">

更新:没关系。如果我使用正则表达式并且匹配它现在可用的字符串。我是这样做的,即我做了(regex).match(string)而不是(string).match(regex)

感谢您的期待!

+0

在我的机器上工作:'sample_str.match(/ [^ |] * $ /)#=>#' – 2014-12-04 14:24:01

+0

我的理解是它也应该在我的工作。但是,如果我先做正则表达式,然后匹配字符串,那么它现在可以在我的机器上运行。我不确定这是什么原因。即使我大多数时候做string.match(正则表达式) – 2014-12-04 14:25:46

+0

这是我得到的时候,当我把它放在控制台上'2.1.2:013> sample_str =“ABC:Something | Hello World” “ABC:Something | Hello世界“ 2.1.2:014> puts sample_str.match(/ [^ |] * $ /) Hello World' – 2014-12-04 14:44:25

回答

7

使用正则表达式似乎过高:

string.split('|').last 
0

下面的正则表达式应该帮助你。

^[\S\s]+?\|([\w\s]+)$ 

不要忘记选择globalmultiline选项。请致电regex demo here