Fredrik
Fredrik

Reputation: 27

Regex replace in c#

I have a sentence like this one:

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

I want to regex replace this sentence so that i get:

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

How can I achieve this? Really been trying all morning, the only thing I've came up with is:

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

Which only gives me:

F and some more text.

Upvotes: 0

Views: 141

Answers (2)

Mark Hurd
Mark Hurd

Reputation: 10931

If you have other replacements with no "alternatives", e.g. [FindThat] with text in between [Find|the|other], you need a slight change to the regex:

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

The explanation:

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

Much of this answer copied from Joey's.

Upvotes: 0

Joey
Joey

Reputation: 354814

You can replace

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

by $1.

A little explanation:

\[      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

Since we stored the first part in the brackets in a capturing group we replace the whole match with the contents of that group.

Quick PowerShell test:

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.

Upvotes: 3

Related Questions