user2229474
user2229474

Reputation:

Regular expression and removing signs

I'm new in regular expressions. I've got a little problem and i can't find the answer. I'm looking for redundant brackets using this regular espression:

public Regex RedundantBrackets = new Regex("[(](\\s?)[a-z](\\s?)[)]");

When i find something i want to modife string in this way:

text1 (text2) text3 => text1 text2 text3 - so as you can se i want only to remove brackets. How can i do this? I was trying to use Replace method, but using it i can only replace every sign of "(text2)".

Thanks in advance!

Upvotes: 1

Views: 108

Answers (3)

ΩmegaMan
ΩmegaMan

Reputation: 31616

Try this replace

Regex.Replace("text1 (text2) text3", // Input
              @"([()])",             // Pattern to match
              string.Empty)          // Item to replace

/* result: text1 text2 text3*/

Explanation

Regex replace looks across the whole string for a match. If it finds a match it will replace that item. So our match pattern looks like this ([()]). Which means this

  1. ( is what is required within the pattern to start the match and needs a closing ) otherwise the match pattern is not balanced.
  2. [] in the pattern says, I am searching for a character, and [ and ] define a set. They are considered set matches. The most common one is [A-Z] which is any set of characters, starting with A and ending in Z. We will define our own set. *Remember [ and ] mean to regex we are looking for 1 character but we specify a set of many characters within that.
  3. ( and ) within our set [()] which also could be specified as [)(] as well means we have a set of two characters. Those two characters are the opening and closing parenthesis ().

So taken all together we are looking to match (1) any character in the set (2) that is either a ( or a ). When that match is found, replace the ( or ) with string.empty.

When we run the regex replace on your text it finds two matches the (text2 and finally the match text2). Those are replaced with string.empty.

Upvotes: 1

user1845851
user1845851

Reputation: 1

this will remove all charaters using regex

finalString = Regex.Replace(finalString, @"[^\w ]", "");

Upvotes: 0

axblount
axblount

Reputation: 2662

First off, it can be handy to use verbatim strings so you don't have to escape the slashes etc.

public Regex RedundantBrackets = new Regex(@"[(]\s?([a-z]+)\s?[)]");

We want to wrap [a-z] in parenthesis because that's what we're trying to capture. We can then use $1 to place that capture into the replacement

RedundantBrackets.Replace("text (text) text", "$1");

EDIT: I forgot to add repetition to [a-z] => [a-z]+

Upvotes: 0

Related Questions