User2400
User2400

Reputation: 2391

Remove a character in a string, provided it is enclosed by brackets

In advance, I haven't learned regex yet (though I'm happy to use one if someone could supply it).

I have strings like this:

"zum Abschluss kommen (nachdrücklich; abgeschlossen werden)".

What I want to do is replace the character ; with : whenever it occurs somewhere in brackets(). Ie: I want my string to end up

"zum Abschluss kommen (nachdrücklich: abgeschlossen werden)".

The thing that is causing me trouble is that there could be any amount of text within the brackets so my usual (clumsy) string manip is not helping me.

Extra example:

"alle Mann an Deck! (Seemannsspr.; ein Kommando)"

->

"alle Mann an Deck! (Seemannsspr.: ein Kommando)"

I can't just Replace() it because the full strings contain ; that I want to keep. Eg:

"das Deck reinigen, scheuern; auf Deck sein; unter, von Deck gehen; alle Mann an Deck! (Seemannsspr.; ein Kommando);"

Got any suggestions?

Upvotes: 2

Views: 722

Answers (2)

user2246674
user2246674

Reputation: 7719

With the restriction that the parenthesis/brackets are not nested or unbalanced, then consider this regular expression that uses a positive look-behind.

This look behind ensures that there is a leftward ( closer than any ) and thus we must be inside a bracket set:

(?<=[(][^)]*);

In use:

Regex.Replace(input, @"(?<=[(][^)]*);", ":");

If the initial constraints are not valid, then this regular expression will work "unpredictably".

Upvotes: 3

Colm Prunty
Colm Prunty

Reputation: 1620

A bit long-winded perhaps.

var a = "Your string";

// Get the bit within them
var bit = a.Substring(a.IndexOf("("), a.IndexOf(")")); 
// Fix the bit
var replaced = bit.Replace(";", ":");
// Put the fixed bit back in the original string
var result = a.Replace(bit, replaced); 

Upvotes: 0

Related Questions