rubyregexrubular

Regex for huge string


I have the below string:

"\n  - MyLibrary1 (= 0.10.0)\n  - AFNetworking (= 1.1.0)\n  - MyLibrary2 (= 3.0.0)\n  - Objective-C-HMTL-Parser (= 0.0.1)\n\n"

I want to create a JSON like this:

{
"MyLibrary1": "0.10.0",
"AFNetworking": "1.1.0",
"MyLibrary2": "3.0.0",
"Objective-C-HMTL-Parser": "0.0.1"
}

For which I need to separate "MyLibrary1" and "0.10.0" and similarly other data to create a string. I am working on a regex to separate data from the string.

I tried /-(.*)/ and /=(.*)/ but this returns me everything after - and =.

Is there a way to get the required data using single regex? Also how do I let regex know that it needs to stop at ( or ). I am using Rubular to test this and whenever I type ( or ) I get "You have an unmatched parenthesis."


Solution

  • You could use the following regex.

    -\s*(\S+)\s*\(\s*=\s*(\S+)\s*\)
    

    Your key match results will be in capturing group #1 and the value match results will be in group #2

    Rubular