Regex for huge string

冷暖自知 提交于 2019-12-24 13:34:14

问题


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


回答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




回答2:


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



回答3:


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

Will return matches:

$1 AFNetworking $2 1.1.0

etc...

Rubular



来源:https://stackoverflow.com/questions/25876223/regex-for-huge-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!