简体   繁体   中英

C# problem with regex

I have a text like this :

string text = "Lorem ipsum dolor sit [1] amet, [3] consectetuer adipiscing  [5/4/9] elit  
Ut odio. Nam sed est. Nam a risus et est[55/12/33/4] iaculis";

I want to get a list of string with all [digit] or all [digit/digit/...] present in my text.

For example:

{"[1]","[3]","[5/4/9]","[55/12/33/4]"} 

for the text above.

How can I do that with regex?

StringCollection resultList = new StringCollection();
Regex regexObj = new Regex(@"\[[\d/]*\]");
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
    resultList.Add(matchResult.Value);
    matchResult = matchResult.NextMatch();
}

Explanation:

\[     # match a literal [
[\d/]* # match any number of digits or /
\]     # match a literal ]

Get the matches as a collection, and get the value from each match into an array like this:

string[] items =
  Regex.Matches(text, @"\[([\d/]+)\]")
  .Cast<Match>()
  .Select(m => m.Groups[0].Value)
  .ToArray();

For simplicity the pattern matches anything that is digits and slashes between brackets, so it would also match something like [//42/] . If you need it to match only the exact occurances, you would need the more complicated pattern @"\\[(\\d+(?:/\\d+)*)\\]" .

Edit:

Here is a version that works with framework 2.0.

List<string> items = new List<string>();
foreach (Match match in Regex.Matches(text, @"\[([\d/]+)\]")) {
  items.Add(m.Groups[0].Value);
}
string regex = @"(\[[\d/]*?\])";

Assuming your input string is stored in a variable input :

Regex regex = new Regex("\\[(\\d/?)*\\]");
MatchCollection matches = regex.Matches(input);

MatchCollection matches holds all of the matches and can be displayed like this:

for (int i = 0; i < matches.Count; i++)
    Console.WriteLine(matches[i].Value);

The above loop outputs:

[1]
[3]
[5/4/9]
[55/12/33/4]

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