tech_human
tech_human

Reputation: 7110

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

Upvotes: 1

Views: 181

Answers (3)

hwnd
hwnd

Reputation: 70732

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

Upvotes: 1

user557597
user557597

Reputation:

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* 
 \)

Upvotes: 1

Chad Grant
Chad Grant

Reputation: 45382

-\s{1}([A-Za-z0-9]+)\s+\(=\s+([0-9\.]+)\)

Will return matches:

$1 AFNetworking $2 1.1.0

etc...

Rubular

Upvotes: 0

Related Questions