Text recognition

  • Thread starter Thread starter Maya
  • Start date Start date
M

Maya

Hello guys,

Is there an easy way in C# to recognize and pull the text between the
"From:" and "To:" strings in the following text:

..... From: John Smith To: Suzan......etc.

So at the end I would have a variable in my code has the value "John Smith"
retrieved from the above text.

Thanks alot.

Maya
 
Maya said:
Is there an easy way in C# to recognize and pull the text between the
"From:" and "To:" strings in the following text:

.... From: John Smith To: Suzan......etc.

So at the end I would have a variable in my code has the value "John
Smith"
retrieved from the above text.

Hi Maya,

If you can rely on the format you gave in your example, this should work:

using System.Text.RegularExpressions;

[...]

Regex r = new Regex("From: (.*) To:");
string s = "From: John Smith To:";
MatchCollection mc = r.Matches(s);
//shows "John Smith"
MessageBox.Show(mc[0].Groups[1].Value);

Cheers

Arne Janning
 
// Starting string
string InputName = "From: John Smith To: Suzan";


// The start Position
int Start = InputName.IndexOf(":")+1;


// The end position
int End = InputName.IndexOf(" T");


// The output
string OutputName = InputName.Substring(Start,End - Start);

// Clear off leading / trailing spaces
OutputName = OutputName.Trim();



Pretty simple stuff
 
Maya,
Check out the classes in the RegularExpressions namespace, namely the Regex
class. Here is a small snippet sample that pulls out the names in the list:

<snip>
using System;
using System.Text.RegularExpressions;

class RegExTest
{
public static void Main()
{
string[] strs = Regex.Split("From: John Smith To: Suzan","From: (.*)
To: ");

foreach( string s in strs )
Console.WriteLine( "-> " + s );
}
}
</snip>

Output is:
<snip>
->
-> John Smith
-> Suzan
</snip>


Patrick Altman
 
Your line - int End = InputName.IndexOf(" T"); - will not work if a " T"
is part of the name..John T Smith or John Thomas...In this case you'll
only output the first name.

You could use the LastIndexOf function to get the position of the last
":" from your string example. ("From: John Smith To: Suzan")

// Starting string
string InputName = "From: John Smith To: Suzan";


// The start Position
int Start = InputName.IndexOf(":")+1;

// The end position
int End = InputName.LastIndexOf(":")-2;

.....
 
Back
Top