开发者

Return a array/list using regex

I would like to return a array string[] or a list List<string> using regex.

I want to compare a string and return all values that starts with [ and end with ].

I am new to regex, so would you plea开发者_JAVA技巧se explain the syntax that you will be using to produce the right results.


var result = Regex.Matches(input, @"\[([^\[\]]*)\]")
    .Cast<Match>()
    .Select(m => m.Groups[1].Value).ToArray();

This regex \[([^\[\]]*)\] means:

  1. \[ - character [
  2. ([^\[\]]*) - any character, excluding [] any number of repetitions, group 1
  3. \] - character ]

Update:

var result = Regex.Matches(input, @"\[[^\[\]]*\]")
    .Cast<Match>()
    .Select(m => m.Value).ToArray();


string pattern = Regex.Escape("[") + "(.*?)]";
string input = "Test [Test2] .. sample text [Test3] ";

MatchCollection matches = Regex.Matches(input, pattern);
var myResultList = new List<string>();
foreach (Match match in matches)
{
    myResultList.Add(match.Value);
}

The result list would contain : [Test2], [Test3]


Stallman says : "When you want to solve a problem using regexp, now you have two problems".

In your case it's something like ^\[.*\]$

http://www.regular-expressions.info/dotnet.html

http://regexlib.com/CheatSheet.aspx?AspxAutoDetectCookieSupport=1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜