【问题标题】:Split string on * character regex在 * 字符正则表达式上拆分字符串
【发布时间】:2014-07-30 21:45:45
【问题描述】:

我试图在 '*' 字符上将一个字符串一分为二,我有以下句子:This is * test string

我已经写了这段代码

            Regex regex = new Regex(@"\\*");
            string[] substrings = regex.Split(text);

            foreach (string match in substrings)
            {
                Console.WriteLine("'{0}'", match);
            }

但我得到以下输出:

'T'h'i's' 'i's'....

但我想要:

'This is ' ' test string'

任何想法如何纠正我的正则表达式?

编辑:我的句子可能有多个“*”字符,在这种情况下,我需要三个句子,例如:

This is * test *

【问题讨论】:

  • 我的句子中可能有多个“*”,String.split 会起作用吗?
  • 书签this page。每当我对正则表达式有疑问时,我都会继续这样做
  • @"..." 不是逐字字符串(即:反斜杠不需要转义)?如果是这样,@"\\*" 将被零个或多个反斜杠分割(即,在每个字符之间)。
  • @MattMcGrath:是的。它将在您指定的字符处将其拆分为多个字符串。你甚至可以有几个不同的角色来打破。 msdn.microsoft.com/en-us/library/b873y76a(v=vs.110).aspx

标签: c# regex


【解决方案1】:

从你的正则表达式中删除双重转义:

Regex regex = new Regex(@"\*");

...

Regex regex = new Regex(@"\*");
String text = "This is * test * more * test";
string[] substrings = regex.Split(text);

foreach (String match in substrings)
         Console.WriteLine("'{0}'", match);

输出

'This is '
' test '
' more '
' test'

【讨论】:

    【解决方案2】:

    “我可能在一个句子中有多个'*',String.split 会起作用吗?”

    是的,您也可以使用 String.Split() 实现您想要做的事情:

    var text = "This is * test *";
    
    var substrings = text.Split('*');
    

    这将为您提供一个包含三个字符串的数组。

    “这是”

    “测试”

    ""

    最后一个字符串是一个空字符串,你可以使用接受StringSplitOptions值的方法重载来省略它:

    var substrings =
        text.Split(new[] {'*'}, StringSplitOptions.RemoveEmptyEntries);
    

    【讨论】:

      【解决方案3】:

      根据您的预期输出,以下代码可能会有所帮助:

      string text = "This is * test string";
      Regex regex = new Regex(@"\*");
      string[] substrings = regex.Split(text);
      string output = "";
      foreach (string match in substrings)
      {   
          output += match;
      }
      Console.WriteLine(output);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        相关资源
        最近更新 更多