tags:

views:

87

answers:

4

I am looking for regular expression to get the match as "HELLO" and "WORLD" separately when the input is any of the following:

"HELLO", "WORLD"
"HELL"O"", WORLD"
"HELL,O","WORLD"

I have tried few combination but none of them seem to work for all the scenarios.

I am looking to have my c# code perform something like this:

string pattern = Regex Pattern;
// input here could be any one of the strings given above
foreach (Match match in Regex.Matches(input, pattern))
{
   // first iteration would give me Hello
   // second iteration would give me World
}
+2  A: 

Try this:

Regex.Match(input, @"^WORLD|HELL[""|O|,]?O[""|O|,]$").Success
Sebastian Brózda
It's an answer to the question. This is a problem many programmers have, they answer the user, but the user did not know how to address the programmer. My brain says "42".
GvS
A: 

Check this article

http://msdn.microsoft.com/en-us/library/8yttk7sy.aspx

Dorababu
A: 

I always found it useful to use an online Regular Expression tester like this one http://www.gskinner.com/RegExr/.

Jake1164
+4  A: 

If you only require it on Hello and World I suggest Sebastian's Answer. It is a perfect approach to this. If you really are putting other data in there, and don't want to capture Hello and World.

Here is another solution:

^([A-Z\"\,]+)[\"\,\s]+([A-Z\"\,]+)$

The only thing is, this will return HELLO and WORLD with the " and , in it.

Then it us up to you to do a replace " and , to nothing in the output strings.

Example:

//RegEx: ^([A-Z\"\,]+)[\"\,\s]+([A-Z\"\,]+)$
    string pattern = "^([A-Z\"\\,]+)[\"\\,\\s]+([A-Z\"\\,]+)$";
    System.Text.RegularExpressions.Regex Reg = new System.Text.RegularExpressions.Regex(pattern);

    string MyInput;

    MyInput = "\"HELLO\",\"WORLD\"";
    MyInput = "\"HELL\"O\"\",WORLD\"";
    MyInput = "\"HELL,O\",\"WORLD\"";

    string First;
    string Second;

    if (Reg.IsMatch(MyInput))
    {
        string[] result;
        result = Reg.Split(MyInput);

        First = result[1].Replace("\"","").Replace(",","");
        Second = result[2].Replace("\"","").Replace(",","");
    }

First and Second would be Hello and World.

Hope this helps. Let me know if you need any further help.

Jimmie Clark