简体   繁体   English

分割字符串的正则表达式

[英]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"

"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: 我希望我的C#代码执行如下操作:

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. 如果仅在“ Hello and World”中要求使用,建议使用塞巴斯蒂安的答案。 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. 如果您确实要在其中放置其他数据,并且不想捕获Hello和World。

Here is another solution: 这是另一种解决方案:

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

The only thing is, this will return HELLO and WORLD with the " and , in it. 唯一的是,这将返回HELLO和WORLD,其中包含“和”。

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. 第一个和第二个是Hello和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/很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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