0

私はこのような文を持っています:

[FindThis|foo|bar] with some text between [FindThis|foo|bar]. [FindThis|foo|bar] and some more text.

この文を正規表現で置き換えて、次のようにします。

FindThis with some text between FindThis. FindThis and some more text.

どうすればこれを達成できますか?本当に午前中ずっと試していましたが、私が思いついたのは次のことだけです。

Regex.Replace(myString, @"\[(\w).*\]", "$1");

それは私にだけ与える:

F and some more text.

4

2 に答える 2

3

交換できます

\[([^|]+)[^\]]+]

によって$1

少し説明:

\[      match the opening bracket
[^|]+   match the first part up to the |
        (a sequence of at least one non-pipe character)
[^\]]+  match the rest in the brackets
        (a sequence of at least one non-closing-bracket character)
]       match the closing bracket

キャプチャグループの括弧内の最初の部分を格納したので、一致全体をそのグループの内容に置き換えます。

クイックPowerShellテスト:

PS> $text = '[FindThis|foo|bar] with some text between [FindThis|foo|bar]. [FindThis|foo|bar] and some more text.'
PS> $text -replace '\[([^|]+)[^\]]+]','$1'
FindThis with some text between FindThis. FindThis and some more text.
于 2012-09-07T10:18:47.460 に答える
0

「代替」のない他の置換がある場合、たとえば[FindThat] with text in between [Find|the|other]、正規表現を少し変更する必要があります。

\[([^|\]]+)[^\]]*]

説明:

\[開き角かっこと一致します  
[^ |\]]+最初の部分を|まで一致させます また ]  
        (少なくとも1つの非パイプ文字または閉じ括弧文字のシーケンス)  
[^\]]*括弧内の残りの部分と一致します  
        (角かっこ以外の文字のシーケンス(なしを含む))  
]閉じ括弧と一致します  

この回答の多くはジョーイのものからコピーされました。

于 2012-09-07T10:58:18.707 に答える