Fadi Fadi - 1 month ago 19
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:

http://sonar.company.com/api/ce/task?id=AVhFxTkyob-dgWZqnfIn


The "closest" I've got was with
/(?=http).[a*-z]*/
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 (
AVhFxTkyob-dgWZqnfIn
) is not static (it changes per build).

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

Answer
>> 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:

(http:\/\/sonar[\w\/.?=-]+task[\w\/.?=-]+(?!.\\n))

.. and return it like this:

string.scan(regex).first.first

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.