简体   繁体   中英

Regular expression to parse [A][B] into A and B

I am trying to separate the following string into a separate lines with regular expression

[property1=text1][property2=text2] 

and the desired result should be

property1=text1
property2=text2

here is my code

string[] attrs = Regex.Split(attr_str, @"\[(.+)\]");

Results is incorrect, am probably doing something wrong

在此处输入图片说明

UPDATE: after applying the suggested answers. Now it shows spaces and empty string

在此处输入图片说明

.+ is a greedy match, so it grabs as much as possible.

Use either

\[([^]]+)\]

or

\[(.+?)\]

In the first case, matching ] is not allowed, so "as much as possible" becomes shorter. The second uses a non-greedy match.

Your dot is grabbing the braces as well. You need to exclude braces:

\[([^]]+)\]

The [^]] matches any character except a close brace.

尝试添加“惰性”说明符:

Regex.Split(attr_str, @"\[(.+?)\]"); 

Try:

var s = "[property1=text1][property2=text2]";
var matches = Regex.Matches(s, @"\[(.+?)\]")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM