有很好的测试工具,可以让你的工作更轻松。我推荐使用URI的extract
方法:
require 'uri'
str = "time=18ms\n[INFO] Calculating CPD for 0 files\n[INFO] CPD calculation finished\n[INFO] Analysis report generated in 325ms, dir size=14 KB\n[INFO] Analysis reports compressed in 187ms, zip size=8 KB\n[INFO] Analysis report uploaded in 31ms\n[INFO] ANALYSIS SUCCESSFUL, you can browse http://sonar.company.com/dashboard/index/com.company.paas.maventestproject:MavenTestProject\n[INFO] Note that you will be able to access the updated dashboard once the server has processed the submitted analysis report\n[INFO] More about the report processing at http://sonar.company.com/api/ce/task?id=AVhFxTkyob-dgWZqnfIn\n[INFO] -----------------------------------------------------------------------"
URI.extract(str)
# => ["http://sonar.company.com/dashboard/index/com.company.paas.maventestproject:MavenTestProject",
# "http://sonar.company.com/api/ce/task?id=AVhFxTkyob-dgWZqnfIn"]
然后,它找到你想要的链接,并使用它的一个简单的事情。
您还需要注意URI为该方带来的所有其他方法,因为它了解如何根据RFC分解和构建URI。
不要推出自己的代码或正则表达式来完成别人已经完成的工作,特别是当代码经过良好测试时。你会避免别人会陷入的陷阱。 URI的作者/维护者管理内置模式,所以我们不需要。而且,它比你想象的要复杂得多,比如:
URI::REGEXP::PATTERN::ABS_URI
"[a-zA-Z][\\-+.a-zA-Z\\d]*:(?:(?://(?:(?:(?:[\\-_.!~*'()a-zA-Z\\d;:&=+$,]|%[a-fA-F\\d]{2})*@)?(?:(?:[a-zA-Z0-9\\-.]|%\\h\\h)+|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|\\[(?:(?:[a-fA-F\\d]{1,4}:)*(?:[a-fA-F\\d]{1,4}|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})|(?:(?:[a-fA-F\\d]{1,4}:)*[a-fA-F\\d]{1,4})?::(?:(?:[a-fA-F\\d]{1,4}:)*(?:[a-fA-F\\d]{1,4}|\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}))?)\\])(?::\\d*)?|(?:[\\-_.!~*'()a-zA-Z\\d$,;:@&=+]|%[a-fA-F\\d]{2})+)(?:/(?:[\\-_.!~*'()a-zA-Z\\d:@&=+$,]|%[a-fA-F\\d]{2})*(?:;(?:[\\-_.!~*'()a-zA-Z\\d:@&=+$,]|%[a-fA-F\\d]{2})*)*(?:/(?:[\\-_.!~*'()a-zA-Z\\d:@&=+$,]|%[a-fA-F\\d]{2})*(?:;(?:[\\-_.!~*'()a-zA-Z\\d:@&=+$,]|%[a-fA-F\\d]{2})*)*)*)?|/(?:[\\-_.!~*'()a-zA-Z\\d:@&=+$,]|%[a-fA-F\\d]{2})*(?:;(?:[\\-_.!~*'()a-zA-Z\\d:@&=+$,]|%[a-fA-F\\d]{2})*)*(?:/(?:[\\-_.!~*'()a-zA-Z\\d:@&=+$,]|%[a-fA-F\\d]{2})*(?:;(?:[\\-_.!~*'()a-zA-Z\\d:@&=+$,]|%[a-fA-F\\d]{2})*)*)*)(?:\\?(?:(?:[\\-_.!~*'()a-zA-Z\\d;/?:@&=+$,\\[\\]]|%[a-fA-F\\d]{2})*))?|(?:[\\-_.!~*'()a-zA-Z\\d;?:@&=+$,]|%[a-fA-F\\d]{2})(?:[\\-_.!~*'()a-zA-Z\\d;/?:@&=+$,\\[\\]]|%[a-fA-F\\d]{2})*)"
这有什么好处:'/ http:\/\/\ S + /'?请参阅[这里](http://www.rubular.com/r/aHG7BZZAmw)进行演示。 –
而不是加载一个字符串中的整个文件,逐行阅读它。这样,您可以快速放弃不以'[INFO]'开头的行。然后用'\ bhttp:// \ S *'检查这一行并解析url。 –
您需要说明用于识别您希望提取的字符串的规则。在你的例子中,你显示你想要的字符串,但不要告诉我们*为什么*它是那个特定的字符串。这就像是说你有一组数字[3,5,8,12,13,20]'并且想知道如何选择'[3,5,13]'。是因为他们是奇数,素数还是别的什么?你需要用问题的陈述开始你的问题,然后在适当的时候提供一个例子。当您修改以澄清时,请不要添加“编辑:”。最后,未来,请将您的例子归结为最基本的要领。 –