0

テキストでいくつかの文字列を検索し、それらの文字列の最初と最後の文字を削除したいと考えています。

例 :

...
...
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
4

2 に答える 2

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("           ");
    }

PSのEnvironment.NewLine代わりに使用する必要があります"\r\n"。より良いアプローチです。

于 2012-11-08T10:45:23.123 に答える
1

物を取り除く必要はありません。そもそも引用符をキャプチャしないでください。したがって、括弧を 1 文字内側に移動します。

"(OK) ([0-9]+) ([A-Za-z_0-9]+) \"((?:(?!\";).)*)\";"
于 2012-11-08T10:45:50.563 に答える