简体   繁体   中英

Regular Expression for splitting string

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
}

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:

^([AZ\\"\\,]+)[\\"\\,\\s]+([AZ\\"\\,]+)$

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.

尝试这个:

Regex.Match(input, @"^WORLD|HELL[""|O|,]?O[""|O|,]$").Success

我总是发现使用像这样的在线正则表达式测试器http://www.gskinner.com/RegExr/很有用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM