2013-03-26 98 views
0

这可能吗?两个字符匹配

从这个字符串:

string = "lsdfh892pr23hr4342pr3j4r\n\nwww.foobar.com•\nyahoogooglebing" 

我想提取"www.foobar.com"

而且,从这个:

string = "lsdfh892pr23hr4342pr3j4r\n\[email protected]•\nyahoogooglebing" 

我想提取"[email protected]"

+0

你有什么要提取?匹配域模式的字符串或新行之间的字符串? – Gael 2013-03-26 01:36:59

+0

字符串\ n \ n和... ... – sambehera 2013-03-26 01:39:34

回答

5

我不知道的Ruby语法,但是这个正则表达式应该工作:

/\n\n([^•]*)•/ 
+0

感谢您的尝试! – sambehera 2013-03-26 01:50:38

+1

这样做。在Ruby中,你可以用'email = string [/ n](/ * ,1]' – Phrogz 2013-03-26 01:53:02

+0

@Progrog我在你的正则表达式后面添加了/ m标志,它工作完美!你能让它成为答案吗?我会接受它! – sambehera 2013-03-26 01:56:11

1

我不会用正则表达式麻烦:

string = "lsdfh892pr23hr4342pr3j4r\n\nwww.foobar.com•\nyahoogooglebing" 
string.split("\n")[2][0..-2] 
=> "www.foobar.com" 

string = "lsdfh892pr23hr4342pr3j4r\n\[email protected]•\nyahoogooglebing" 
string.split("\n")[2][0..-2] 
=> "[email protected]" 
+1

split是一种简单的正则表达式,在这里,它不会简化代码,使提取更加灵活(您不知道每次电子邮件或域是否位于第三行),并且不会提高性能。 – Gael 2013-03-26 02:16:06

+0

是的,'split'强制字符串'“\ n”'为正则表达式,但是,它减轻了OP需要维护任何更复杂的模式。由OP决定该字符串是否始终在第三行上有站点名称。在这种情况下,它与给出的数据样本一致,并且假设总是有一个“子弹”或两个程序“\ n”同样安全。 – 2013-03-26 02:33:32

+0

好吧,正则表达式可能很复杂。然而,我认为我更喜欢具有良好语义的代码。而'split'并不是专门提取内容的。 – Gael 2013-03-26 03:28:05