-1

I am unable to get matched content inside a file with regex. My requirement is user provide some text in textbox 1 and some text in textbox 2. The regex method should search the file by combination of both texts from textbox. As of now I am able to find match with single search provided by user.

Here is the code:

private Regex R = null;

public void GetFileInfo(string textbox1val)
{
   if (this.R.IsMatch(text))
   {
      // my other code goes here....
   }
}

//on button click I am passing textbox text to regex and  to GetFileInfomethod
private void button1_Click(object sender, EventArgs e)
{        
   this.R = new Regex(textbox1.Text);
   GetFileInfo(textbox1.Text);
}

Please help me on this question, thanks in advance for your help.

Regards, Aditya.J

Bruno Ferreira
  • 466
  • 7
  • 17
Adithya
  • 183
  • 1
  • 2
  • 16
  • 1
    You have not included any requirements, nor described what is wrong with your code. Is the user defined text a regular epression or a literal text? – Wiktor Stribiżew Mar 22 '17 at 12:47
  • 1
    What is supposed to be in the text boxes, plain text or regular expressions? – Dmitry Egorov Mar 22 '17 at 12:49
  • Thank you all for your quick responses, Wiktor Stribiżew user will be providing plane text and by the way Dmitry Egorov thanks for your solution this is what I am looking for. – Adithya Mar 22 '17 at 13:22

1 Answers1

1

Provided the text boxes contain exact text to be searched for (as the textual description suggests) and not regular expressions (despite the code sample), your regex initialization may be either

this.R = new Regex(string.Format("{0}|{1}",
    Regex.Escape(textbox1.Text), Regex.Escape(textbox2.Text)));

if finding only one of the user provided strings is OK, or

this.R = new Regex(string.Format("^(?=.*{0})(?=.*{1})",
    Regex.Escape(textbox1.Text), Regex.Escape(textbox2.Text)));

if both of the user provided string should be found in the file.

Please notice the Regex.Escape to escape any regex special characters which a user may potentially type in.

The first regex is a simple alternation.

The second regex employs positive lookbehinds and the used construct is explained here.

Community
  • 1
  • 1
Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40