C# 字符串上的C正则表达式

C# 字符串上的C正则表达式,c#,regex,C#,Regex,我试图在一个字符串中找到一个字符串,现在我在 string str4; var str5 = " type: '"); foreach (string str6 in response.Split(new char[] { '\n' })) { if (str6.StartsWith(str5)) { str4 = str6.Replace(str5, "").Replace(" ", "").Replace("',", ""); break

我试图在一个字符串中找到一个字符串,现在我在

string str4;

var str5 = "   type: '");
foreach (string str6 in response.Split(new char[] { '\n' }))
{
    if (str6.StartsWith(str5))
    {
        str4 = str6.Replace(str5, "").Replace(" ", "").Replace("',", "");
        break;
    }
}
它的工作原理与预期相符&将从

type: '
这方面的例子是

type: ' EXAMPLE ',
回路后输出

EXAMPLE

现在的问题是,偶尔“type:”开头的空格会有所不同,因此有时它可能与我提供的空格相等,有时则可能不相等

我试着用正则表达式,这样我可以做一些事情,比如

string str5 = "Regex(*)type: '"

当然这在用法上是完全不正确的,但我的示例显示了*的用法,它等于任何可能性,因此无论空格的数量如何,我仍然能够从类型中提取内部文本。

您可以使用.Trim、.TrimStart和.trimsend。使用正则表达式看起来像是额外的开销,您并不真正需要它。

这里我们只需在所需输出前后添加可选空格,例如,我们可以从以下表达式开始,例如:

type:(\s+)?'(\s+)?(.+?)(\s+)?',
或:

如果我们可能有',我们将表达式扩展为:

type:(\s+)?['"](\s+)?(.+?)(\s+)?['"]
测验 正则表达式电路 可视化正则表达式:


如果这只是一个输入变化非常有限的简单提取任务,则可以使用普通正则表达式:

var response = @"[{
   type: 'foo',
something: 'bar',
},
{
  type: 'baz',
  something: 'bat'
}]";
var types = Regex.Matches(response, @"\s*type\:\s*\'(.+)\'")
    .Cast<Match>()
    .Select(m => m.Groups.Cast<Group>().Skip(1).Single().Value);
但听起来您可能正在尝试为编程或标记语言编写解析器。如果是这样的话,我强烈建议你不要尝试用正则表达式来做。当您开始尝试处理诸如转义字符串类型:“I'm a type:”之类的事情时,正则表达式就会变得非常棘手


如果您的输入是JSON等标准格式,请使用该格式的解析库。如果没有,还有像Sprache这样的库,可以轻松创建功能强大的自定义解析器。

首先,如果要使用正则表达式,请在此处试用正则表达式字符串:

第二,如果你能避免使用正则表达式,我建议你这样做。如果开发人员使用正则表达式解决问题,那么现在他有两个问题。如果你没有使用过很多正则表达式,那么正则表达式可能会很棘手。话虽如此,这里有另一个基于正则表达式的解决方案。此外,通常有几种方法来构造正则表达式字符串

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] SampleInputList = new string[]
            {
                "type:EXAMPLE",
                " type: EXAMPLE ",
                "   type:  EXAMPLE  "
            };

            // The following is a non-capture group indicator: (?:)
            // non-capture groups are a good way to organize parts
            // of your regex string and can help you visualize the
            // parts that are just markers like 'type:' vs. the parts
            // that you want to actually manipulate in the code.
            Regex expression = new Regex(@"(?:\s*type\:\s*)([A-Za-z]*)");

            foreach (string Sample in SampleInputList)
            {
                MatchCollection matches = expression.Matches(Sample);
                if (matches.Count > 0)
                {
                    GroupCollection groups = matches[0].Groups;
                    if (groups.Count > 1)
                    {
                        Console.WriteLine(groups[1].Value);
                    }
                }
            }
        }
    }
}

现在的问题是,偶尔“type:”开头的空格会有所不同,因此有时它可能与我提供的空格相等,有时则可能不相等。这个答案过于简化了问题的实质needed@CamiloTerevinto不是真的。TrimStart:从当前字符串对象中删除数组中指定的一组字符的所有前导匹配项。无论是4个空格还是400个空格,都会将它们全部删除。。。。输入类型是:“EXAMPLE”,所以我不确定为什么您认为只调用TrimStart/TrimEnd会work@CamiloTerevinto字体我读到了。这是一个简单的修剪、替换和再次修剪。这只是我的错误,但是Mark花时间阅读了完整的描述,并注意到我提到的空格位于字符串的开头,但是从我的示例中,我没有正确地添加空格。应该不鼓励仅仅为了使用正则表达式而使用正则表达式。它提供了额外的开销和高度不可读的代码。@CamiloterienTo两个答案都可以,我写错了解释,空格在字符串的开头,所以TrimStart和TrimEnd也可以。。谢谢大家的意见!感谢你们三位的支持。像str4、str5或str6这样的变量名对R2-D2有好处,对人类没有好处。选择像result而不是str4、searchPattern而不是str5、line而不是str6这样会说话的名字。@OlivierJacot Descombes感谢您的输入,我将在下一个问题中考虑到这一点:
var response = @"[{
   type: 'foo',
something: 'bar',
},
{
  type: 'baz',
  something: 'bat'
}]";
var types = Regex.Matches(response, @"\s*type\:\s*\'(.+)\'")
    .Cast<Match>()
    .Select(m => m.Groups.Cast<Group>().Skip(1).Single().Value);
using System;
using System.Text.RegularExpressions;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] SampleInputList = new string[]
            {
                "type:EXAMPLE",
                " type: EXAMPLE ",
                "   type:  EXAMPLE  "
            };

            // The following is a non-capture group indicator: (?:)
            // non-capture groups are a good way to organize parts
            // of your regex string and can help you visualize the
            // parts that are just markers like 'type:' vs. the parts
            // that you want to actually manipulate in the code.
            Regex expression = new Regex(@"(?:\s*type\:\s*)([A-Za-z]*)");

            foreach (string Sample in SampleInputList)
            {
                MatchCollection matches = expression.Matches(Sample);
                if (matches.Count > 0)
                {
                    GroupCollection groups = matches[0].Groups;
                    if (groups.Count > 1)
                    {
                        Console.WriteLine(groups[1].Value);
                    }
                }
            }
        }
    }
}