The Regular Expression is simple:
\[([^][]+)\]
This says that a match consists of the '[' character followed by 1 or more
characters that are neither '[' nor ']' and that is followed by a ']'
character.
It also puts the actual contents of the brackets into a group, Group 1, as
in the following example:
Hi there. My name is [Alex]. My brother's name is [Billy].
In this example, "[Alex]" is a match, and so is "[Billy]". In the "Alex"
match, "Alex" is Group 1. In the "Billy" match, "Billy" is Group 1.
I would use the Regex.Replace overload which takes a string and a
MatchEvaluator delegate. A MatchEvaluator delegate is a method that takes a
System.Text.RegularExpressions.Match object as an argument, and returns the
replacement string for that Match. The Replace method replaces each Match
with the MatchEvaluator, and thus replaces the entire string. It is the
method that does the actual replacing. Example:
// MatchEvaluator delegate
private string bracketReplacer(Match m)
{
// strips the brackets and returns the value enclosed in them.
return m.Groups[1].Value;
}
// Replacement Function
public string ReplaceBrackets(string s)
{
Regex regex = new Regex(@"\[([^][]+)\]");
return regex.Replace(s, new MatchEvaluator(bracketReplacer));
}
--
HTH,
Kevin Spencer
Microsoft MVP
Chicken Salad Surgery
Who is Mighty Abbott? A twin-turret scalawag.
"Alex Maghen" <Al********@newsgroup.nospamwrote in message
news:34**********************************@microsof t.com...
This is a bit of an abuse of this group. Just a nit, but I'm hoping
someone
really good with Regular Expressions can help me out here.
I need to write a regular expression that will do the following:
Search a whole blob of text (including newlines and everything).
Find any text enclosed in brackets ([xyz]), and replace it with a string I
provide and then concatenate the text that had been enclosed in the
brakets,
without the brakets.
So, for example:
Input String:
"Hi there. My name is [Alex]. My brother's name is [Billy]."
Prepend Parameter:
"Mr. "
For this example, the output would be:
"Hi there. My name is Mr. Alex. My brother's name is Mr. Billy."
I'm sure that this is very simple for people who know RegEx's. I ain't one
of those people. Anyone's help would be MOST appreciated.
Alex