简体   繁体   English

正则表达式的C#问题

[英]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/] . 为简单起见,该模式匹配方括号之间的数字和斜杠,因此它也将匹配[//42/] If you need it to match only the exact occurances, you would need the more complicated pattern @"\\[(\\d+(?:/\\d+)*)\\]" . 如果只需要它来匹配确切的出现次数,则需要更复杂的模式@"\\[(\\d+(?:/\\d+)*)\\]"

Edit: 编辑:

Here is a version that works with framework 2.0. 这是与框架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 : 假设您的输入字符串存储在变量input

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

MatchCollection matches holds all of the matches and can be displayed like this: MatchCollection matches包含所有匹配项,可以这样显示:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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