1

I need a Regex pattern which is going to be used to remove some numbers at specific positions.

My string format is like this: xxxx - 2013-xxxxxx9 xxxxxxxx9, the '9' in the string means a number or doesn't exist.

The code I wrote is like this:

  string str= "dddd - 2013-0Winter1 morning2";
  Regex pattrn = new Regex(".* - ([0-9]{4}-).*([1-9]?) .*([1-9]?)$");
  Match match = pattern.Match(me);
  for (int index = match.Groups.Count - 1; index > 0; index--)
  {
    str = str.Remove(match.Groups[index].Index, match.Groups[index].Length);
  }

When I run this, match.Groups[2] and match.Groups[3]'s value are blank. But I want to find '2013','1' and '2' in the string.

The result is:

"dddd - 0Winter1 morning2";

The result I want is:

"dddd - 0Winter morning";

Does anybody know why?

4

1 回答 1

2

问题是你.*是贪婪的,所以它吞噬了([1-9]?)它之后的东西。如果您使用非贪心量词( .*?),您将得到您想要的结果:

string str = "dddd - 2013-0Winter1 morning2";
Regex pattern = new Regex("^.* - ([0-9]{4}-).*?([1-9]?) .*?([1-9]?)$");
Match match = pattern.Match(str);
for (int index = match.Groups.Count - 1; index > 0; index--)
{
    str = str.Remove(match.Groups[index].Index, match.Groups[index].Length);
}

Console.WriteLine(str); // dddd - 0Winter morning

当然,这将产生相同的结果:

string str = "dddd - 2013-0Winter1 morning2";
str = Regex.Replace(str, @"^(\w*? [0-9]{4}-\w*?)[1-9]? (\w*?)[1-9]?$", "$1 $2");
Console.WriteLine(str); // dddd - 0Winter morning
于 2013-07-18T21:26:45.933 回答