Reputation: 111
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
}
Upvotes: 0
Views: 210
Reputation: 1868
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.
Upvotes: 4
Reputation: 12369
I always found it useful to use an online Regular Expression tester like this one http://www.gskinner.com/RegExr/.
Upvotes: 0
Reputation: 879
Try this:
Regex.Match(input, @"^WORLD|HELL[""|O|,]?O[""|O|,]$").Success
Upvotes: 2