regexrubular

Adding words in regex


I have this string below:

"\n  - MyLibrary1 (from ‘repo_name’, branch ‘master’)\n  - AFNetworking (= 1.1.0)\n  - MyLibrary2 (from ‘repo_name’, branch ‘master’)\n  - Objective-C-HMTL-Parser (= 0.0.1)\n\n"

Of which I wish to extract the data and create a JSON like this below:

{
"MyLibrary1": “master”,
"AFNetworking": "1.1.0",
"MyLibrary2": “master”,
"Objective-C-HMTL-Parser": "0.0.1"
}

With the help of my previous post (Regex for huge string), I was able to get the data after '=' in the string.

I am working on modifying the same regex to get the word 'master'. With whatever I tried, in my match object I get first part as "MyLibrary1" and second part as "from ‘repo_name’, branch ‘master’".

Question: Can a regex contain a word? Can I add word 'branch' to get the word 'master' off the string?

Regex I tried - -\s*(.?)\s(\s*(.?)\s)

Rubular link - http://rubular.com/r/gPLIa0xqRC


Solution

  • Yes, you can use the alternation operator in context to specify that it either matches an equal sign or any character except ) "zero or more" times preceded by the word "branch".

    -\s*(\S+)\s*\(\s*(?:=|[^)]*\bbranch)\s*(\S+)\s*\)
    

    Rubular