1

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."

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
tech_human
  • 6,592
  • 16
  • 65
  • 107

3 Answers3

1

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

hwnd
  • 69,796
  • 4
  • 95
  • 132
  • I see this works in Rubular, but any idea why is it just retuning me the first data in ruby i.e. it returns me "- MyLibrary1 (= 0.10.0)"? Am I missing something here? All I did was I stored my string in a variable named dependencies and then I use the regex on it "dependencies[/-\s*(\S+)\s*(\s*=\s*(\S+))/]" – tech_human Sep 16 '14 at 19:30
  • You need to print the match groups. Probably use scan as well – hwnd Sep 16 '14 at 19:52
  • Yup scan helps. Thanks! – tech_human Sep 16 '14 at 20:34
1

Seems to work with your sample.

 # -\s*(.*?)\s*\(\s*=\s*(.*?)\s*\)

 -
 \s* 
 ( .*? )        # (1)
 \s* 
 \(
 \s* 
 =
 \s* 
 ( .*? )        # (2)
 \s* 
 \)

Or, you could put in some mild validation. Note that the lazy quantifiers are used just
to trim whitespace.

 # -\s*([^()=]*?)\s*\(\s*=\s*([^()=-]*?)\s*\)

 -
 \s* 
 ( [^()=]*? )  # (1)
 \s* 
 \(
 \s* 
 =
 \s* 
 ( [^()=-]*? )  # (2)
 \s* 
 \)
  • Your solution is working on rubular, but any idea why is it just returning me just the first data when I use it in ruby? Do I need to add something while using it in ruby? I am doing dependencies.match(/-\s*(.*?)\s*\(\s*=\s*(.*?)\s*\)/) where "dependencies" variable has the string in it. – tech_human Sep 16 '14 at 19:47
  • In ruby it just returns me # – tech_human Sep 16 '14 at 19:48
  • Should just use a search function in global scope (global modifier). Also, what's returned that is of interest to you is in capture groups 1 and 2, not the whole match. –  Sep 16 '14 at 19:55
  • From your string its 1:"`MyLibrary1`" 2:"`0.10.0`" –  Sep 16 '14 at 20:15
0
-\s{1}([A-Za-z0-9]+)\s+\(=\s+([0-9\.]+)\)

Will return matches:

$1 AFNetworking $2 1.1.0

etc...

Rubular

Chad Grant
  • 44,326
  • 9
  • 65
  • 80