Fadi Fadi - 1 year ago 114
Ruby Question

regex get a particular part of a string

I'm creating a ruby (sinatra) app and part of the app I'm trying to parse a (really long) string and use regex to pull out a link from it, I'm having trouble with the regex part. Here's an excerpt of the long string with the relevant information that I need to extract out of it:

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] -----------------------------------------------------------------------

I need to be able to pull the following from that long string:


The "closest" I've got was with
but that's not even close to what I need (as it found 615 matches instead of 1).

EDIT: The problem also is that the id (
) is not static (it changes per build).

EDIT2: I've been using Rubular.com to find the proper regex I need to use.

Answer Source
>> string = '[your long string here]'
>> regex = /(http:[\w\/.?=-]+)(\\n)/
>> string.scan(regex).first.first
=> "http://sonar.company.com/api/ce/task?id=AVhFxTkyob-dgWZqnfIn"

Following the example above, I ended up modifying the regex to the following:


.. and return it like this:


The reason why I modified the regex is because the previous regex, ended up with a lot of results when plugging in the full string rather than the excerpt that's in the OP.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download