using Regex to split a string

D

dchan1

String line = " I am new to c# ";

How to use Regex to split the string so that It would return a String array
with:

token[0] = "I"
token[1] = "am"
token[2] = "new"
token[3] = "to"
token[4] = "c#"


Please help.

thanks
 
G

Guest

//regex expression to take out any ctrl + somekey values
private System.Text.RegularExpressions.Regex Regx = new
System.Text.RegularExpressions.Regex(@"[\cA-\cZ]");
private char[] _split = { ' ' };

string mystring = " I am new to c# ";
mystring = mystring.Replace(" "," ");
mystring = mystring.Replace(" "," ").Trim();
string[] line = null;

//regx implementation
line = Regx.Replace(mystring,"").ToString().Split(_split);


output would be:
line [0] = "I"
line [1] = "am"
line [2] = "new"
line [3] = "to"
line [4] = "c#"

Cheers!

Rob
 
G

Guest

BTW:

If you are just using a string veriable and not needing to take care of
regualar expression issues, you should just use the split() from the string

string mystring = " I am new to c# ";
char[] _split= " ".ToCharArray();

mystring = mystring.Replace(" "," ");
mystring = mystring.Replace(" "," ").Trim();

string[] line = mystring.ToString().Split(_split) ;

output would be:
line [0] = "I"
line [1] = "am"
line [2] = "new"
line [3] = "to"
line [4] = "c#"

Cheers!

Rob
 
J

Jay B. Harlow [MVP - Outlook]

dchan1,
Have you tried:

String lines[] = RegEx.Split(line.Trim(), "\s+");

Which says to removing leading & trailing spaces, when split the result
based on one or more white space characters.

Hope this helps
Jay
 
J

Jay B. Harlow [MVP - Outlook]

Doh!
Which says to removing leading & trailing spaces, when split the result
<grammar check>
Which says to remove leading & trailing spaces, then split the result
</grammar check

Some days I worry about me... :)

Jay

Jay B. Harlow said:
dchan1,
Have you tried:

String lines[] = RegEx.Split(line.Trim(), "\s+");

Which says to removing leading & trailing spaces, when split the result
based on one or more white space characters.

Hope this helps
Jay

dchan1 said:
String line = " I am new to c# ";

How to use Regex to split the string so that It would return a String
array
with:

token[0] = "I"
token[1] = "am"
token[2] = "new"
token[3] = "to"
token[4] = "c#"


Please help.

thanks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top