0

I am trying to find some patterns. they can be:

1. "fourty|40;TOFIND|1234;fifty|50"
2. "TOFIND|1234;fifty|50"
3. "fourty|40;TOFIND|1234"

as you can see, the TOFIND|1234 can appear inside the statement (before ; and after ;), or it can have only before ; or it can have none.

It should NOT include examples:

MTOFIND|1234;
;TOFIND|1234Q

How can I find it?

I tried: Regex re = new Regex("TOFIND|1234" + "[;?]");

But I am not sure its correct.

Please help!

Thanks

3
  • You should propose what some negative samples could be, e.g., what if there was XTOFIND|1234, or TOFIND|12345. Commented May 24, 2011 at 15:37
  • would you like to extract the TOFIND from the line? Or do you want to get only those lines that have TOFIND in it? Commented May 24, 2011 at 15:37
  • I need it to support only beginning is empty, end is empty or ; before or ; at the end Commented May 25, 2011 at 6:51

6 Answers 6

1

What about any character before or after the exact string TOFIND|1234?

Regex re = new Regex(".*(TOFIND\|1234).*");
Sign up to request clarification or add additional context in comments.

1 Comment

Not allowed. Only ^ or $ (respectively) or only ; that can appear at the beginning or end
0
Regex re = new Regex("(?:[^;])TOFIND\|1234(?=[;$])");

Comments

0

You my try this: ";?TOFIND|1234;?" This will include ";"s in the match.

Comments

0

I would do it like this

string FindIt(string inStr)
{
    for each (string item in inStr.Split(new char [] {';'}))
    {
       string [] eles = item.Split(new char [] {'|'});
         if (eles[0] == "TOFIND")
           return eles[1];
    }
    return "";
}

Comments

0

To get the lines that contain TOFIND

@"TOFIND\|.*|.*;TOFIND.*"

I found this tool over here to be of great help: Rad Software Regular Expression Designer

Comments

0

Based on your comments and edits, here we go... This is the Regex that you could use:

Regex r = new Regex(@";?[^\w](TOFIND\|1234)[^\w];?");

So, using the folowing samples:

1. "fourty|40;TOFIND|1234;fifty|50"
2. "TOFIND|1234;fifty|50"
3. "fourty|40;TOFIND|1234"
4. "MTOFIND|1234;"
5. ";TOFIND|1234Q"
6. "some|15;TOFIND|1234;"
7. ";TOFIND|1234;blabla|100"

It will match the lines 1, 2, 3, 6 and 7.

Let's explain the rules:

";?"  // We need 0 or 1 semi-colon before.
"[^\w]"  // We can't have any char (a-zA-Z0-9) before.
"(TOFIND\|1234)"  // We must have exactly TOFIND|1234.
"[^\w]"  // We can't have any char after.
";?"  // We need 0 or 1 semi-colon after.

If I understood well all your needs, thats it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.