Regex Issue

  • Thread starter Thread starter DevBoy
  • Start date Start date
D

DevBoy

I am in need of parsing string based on characters like / or { or } or ^

However, anytime I try and run the following code I do not the proper
results (It always returns the same string unparsed.

Regex rx = new Regex("{");
string[] segmentData = rx.split(str);

Any helpful hints?
 
Regex rx = new Regex("{");
string[] segmentData = rx.split(str);

I don't see a problem. I emulated your code and it ran perfectly.
const string mystring = "this{is{the{way{we{wash{our{hair";
Regex rx = new Regex("{");
string[] segmentData = rx.Split(mystring);
for ( int ix = 0; ix < segmentData.Length; ix++ )
{
Console.WriteLine("Segment Data for {0} is {1}", ix,
segmentData[ix]);
}

Segment Data for 0 is this
Segment Data for 1 is is
Segment Data for 2 is the
Segment Data for 3 is way
Segment Data for 4 is we
Segment Data for 5 is wash
Segment Data for 6 is our
Segment Data for 7 is hair
 
I apologize for some confusion. I am having an issue currently with the
following character in regex'ing ^.
 
I apologize for some confusion. I am having an issue currently with the
following character in regex'ing ^.
In that case, you do need to escape the characters"

const string mystring = @"this/is{the}way^we/wash{our^hair";

Regex rx = new Regex("/|\\{|\\}|\\^");
string[] segmentData = rx.Split(mystring);
for ( int ix = 0; ix < segmentData.Length; ix++ )
{
Console.WriteLine("Segment Data for {0} is {1}", ix,
segmentData[ix]);
}

Read up on it here: http://tinyurl.com/3g4td
 
These are control chars in Regex: . $ ^ { [ ( | ) ] } * + ? \

so if you want to use them as literal string, you have to append "\" infront
of the char.

Example: text = "hahaha :-)"

and you want to extract the smile ":-)"

// @ tell CSharp to treat everything in the string as a literal string
without any control char
// since ")" is a control char in regex, you have to pad, ")" becomes "\)"
Regex.Match(text, @":-\)");


or without the @ key
// since "\" is a control in the string context you have to pad that too
Regex.Match(text, ":-\\)");


Hope that helps,

Du
 
Back
Top