在文本中查找字符串,删除第一个和最后一个字符

时间:2012-11-08 10:37:00

标签: c# regex string

我在文本中搜索某些字符串,并希望删除这些字符串中的第一个和最后一个字符。

示例:

...
...
OK 125 ab_D9 "can be "this" or; can not be "this" ";
...
OK 673 e_IO1_ "hello; is strong
or maybe not strong";
...

所以我使用代码查找所有以OK开头的字符串并从4组“...”中删除:

tmp = fin.ReadToEnd();
var matches = Regex.Matches(tmp, "(OK) ([0-9]+) ([A-Za-z_0-9]+) (\"(?:(?!\";).)*\");", RegexOptions.Singleline);
for (int i = 0; i < matches.Count; i++)
    {
         matches[i].Groups[4].Value.Remove(0);

         matches[i].Groups[4].Value.Remove(matches[i].Groups[4].Value.ToString().Length - 1);
         Console.WriteLine(matches[i].Groups[1].Value + "\r\n" + "\r\n" + "\r\n" + matches[i].Groups[2].Value + "\r\n" + "\r\n" + matches[i].Groups[3].Value + "\r\n" + "\r\n" + "\r\n" + matches[i].Groups[4].Value);
         Console.WriteLine("           ");
    }

但它不会删除第4组中的第一个和最后一个字符。我做错了什么?

我的结果应该是:

 OK

 125

 ab_D9


 can be "this" or; can not be "this" 


 OK

 673

 e_IO1

 hello; is strong
 or maybe not strong

2 个答案:

答案 0 :(得分:1)

您应该分配Substring()Remove()方法的结果。它们不会更改现有字符串,但会返回您需要分配给相同或其他字符串变量的已更改字符串。检查代码:

tmp = fin.ReadToEnd();
var matches = Regex.Matches(tmp, "(OK) ([0-9]+) ([A-Za-z_0-9]+) (\"(?:(?!\";).)*\");", RegexOptions.Singleline);
for (int i = 0; i < matches.Count; i++)
    {
         string str = matches[i].Groups[4].Value.Substring(0);

         str = str.Remove(str.Length - 1);
         Console.WriteLine(matches[i].Groups[1].Value + "\r\n" + "\r\n" + "\r\n" + matches[i].Groups[2].Value + "\r\n" + "\r\n" + matches[i].Groups[3].Value + "\r\n" + "\r\n" + "\r\n" + str);
         Console.WriteLine("           ");
    }

P.S。您应该使用Environment.NewLine代替"\r\n",这是更好的方法。

答案 1 :(得分:1)

没有必要删除东西。只是不要首先捕获引号。所以将括号向内移动一个字符。

"(OK) ([0-9]+) ([A-Za-z_0-9]+) \"((?:(?!\";).)*)\";"
相关问题