I'm trying to use a regular expression to retrieve text from RichTextBox
Posted
by Simon
on Stack Overflow
See other posts from Stack Overflow
or by Simon
Published on 2010-03-30T12:49:23Z
Indexed on
2010/03/30
12:53 UTC
Read the original article
Hit count: 337
Hello!
As the header is implying I'm trying to retrieve a certain line of numbers from a richtextbox and then put it into a separate textbox. I've tried this code below but it doesn't wanna work with me. It's probably way wrong and there's probably easier ways of doing it but I'm quite new to this stuff and I would appreciate all the help I can get in this matter.
I have a textbox called tbPersNr;
A RichTextBox called tbText;
A button which is called btnGet;
string regPattern = @"\\d{6}-\\d{4}";
int indexOfSearch = 0;
private void btnGet_Click(object sender, EventArgs e)
{
int startIndex = 0;
if (tbText.Text.Length > 0)
{
startIndex = HittaPersNr(regPattern, startIndex, tbText.Text.Length);
}
if (startIndex > 0)
{
this.tbPersNr.Text = regPattern.ToString();
}
}
public int HittaPersNr(string txtToSearch, int searchStart, int searchEnd)
{
// Setting default value to -1.
int retVal = -1;
// Validating start of the search
// om indexOfSearch = -1, slutar sökningen
if (searchStart >= 0 && indexOfSearch >= 0)
{
// Validating end of search
if (searchEnd > searchStart || searchEnd == -1)
{
// Searching for results in richtextbox
indexOfSearch = tbText.Find(regPattern, searchStart, searchEnd, RichTextBoxFinds.None);
// Validating if search resulted in any finds.
if (indexOfSearch != -1)
{
// putting index to value in the text.
retVal = indexOfSearch;
}
}
}
return retVal;
}
}
}
Cheers
© Stack Overflow or respective owner