3

私はフォームに文字列を持っています[abc].[some other string].[can.also.contain.periods].[our match]

私は今、文字列「私たちの試合」(つまり、括弧なし)に一致させたいので、ルックアラウンドなどで遊んだ。正しい一致が得られましたが、これはきれいな解決策ではないと思います。

(?<=\.?\[)     starts with '[' or '.['
([^\[]*)      our match, i couldn't find a way to not use a negated character group
              `.*?` non-greedy did not work as expected with lookarounds,
              it would still match from the first match
              (matches might contain escaped brackets)
(?=\]$)       string ends with an ]

言語は .net/c# です。正規表現を使用しないより簡単な解決策があれば、私も知りたいです

私を本当にいらいらさせているのは、(.*?)後読みでは非貪欲が機能しないように見えるため、文字列をキャプチャするために使用できないという事実です。

私も試しました: Regex.Split(str, @"\]\.\[").Last().TrimEnd(']');、しかし、私はこの解決策を本当に誇りに思っていません

4

4 に答える 4

5

以下はトリックを行う必要があります。文字列が最後の一致の後に終了すると仮定します。

string input = "[abc].[some other string].[can.also.contain.periods].[our match]";

var search = new Regex("\\.\\[(.*?)\\]$", RegexOptions.RightToLeft);

string ourMatch = search.Match(input).Groups[1]);
于 2010-06-25T11:50:32.763 に答える
4

入力形式を保証でき、それが必要な最後のエントリであると仮定すると、次のLastIndexOfように使用できます。

string input = "[abc].[some other string].[can.also.contain.periods].[our match]";

int lastBracket = input.LastIndexOf("[");
string result = input.Substring(lastBracket + 1, input.Length - lastBracket - 2);
于 2010-06-25T11:32:26.410 に答える
0

いくつかのオプションがあります:

  • RegexOptions.RightToLeft- はい、.NET 正規表現はこれを行うことができます! これを使って!
  • 全体を貪欲な接頭辞で一致させ、括弧を使用して興味のある接尾辞をキャプチャします

参考文献

于 2010-06-25T10:25:23.153 に答える
0

String.Split() を使用:

string input = "[abc].[some other string].[can.also.contain.periods].[our match]";
char[] seps = {'[',']','\\'};
string[] splitted = input.Split(seps,StringSplitOptions.RemoveEmptyEntries);

splitted[7] で「out match」が得られ、can.also.contain.periods は 1 つの文字列として残されます (splitted[4])

編集: 配列は [] 内に文字列を持ち、次に . など、可変数のグループがある場合は、それを使用して必要な値を取得できます (または「.」だけの文字列を削除します)。

'\[abc\]' のようなケースを処理するために、区切り記号にバックスラッシュを追加するように編集

Edit2: ネストされた [] の場合:

string input = @"[abc].[some other string].[can.also.contain.periods].[our [the] match]";
string[] seps2 = { "].["};
string[] splitted = input.Split(seps2, StringSplitOptions.RemoveEmptyEntries);

最後の要素 (インデックス 3) で [the] match] を使用すると、余分な ] を削除する必要があります。

于 2010-06-25T10:04:38.630 に答える