C# 字符串的正则表达式

标签 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;
    }
}

它按预期工作并且将从中获取文本

type: '

这个例子是

type: ' EXAMPLE ',

循环后的输出

EXAMPLE

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

我试图使用正则表达式,这样我就可以做一些事情,例如,

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

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

最佳答案

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

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

Demo

或者:

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

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

type:(\s+)?['"](\s+)?(.+?)(\s+)?['"]

测试

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"type:(\s+)?'(\s+)?(.+?)(\s+)?',";
        string input = @"type:' EXAMPLE ',
type: ' EXAMPLE ',
type:    '   EXAMPLE    ',
type:    '   Any other EXAMPLE we might have   ',";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

正则表达式电路

jex.im可视化正则表达式:

enter image description here

关于C# 字符串的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56528633/

相关文章:

c# - 如何为从源文件编译的应用程序分配自定义图标?

c# - 如何使 Roslyn Analyzer 项目成为可传递依赖项?

c# - 使用委托(delegate)类型与方法

ruby - 如何在 Ruby 的正则表达式中使用 şŞıİçÇöÖüÜÜĞğ 字符?

c# - 使用包含的 Linq 查询不起作用

c# htmlDecode 实体数大于 127

javascript - 正则表达式:匹配 MSSQL 连接字符串中的密码,考虑引号换行

sql - 在 pgSQL select 中使用正则表达式捕获

Python:字符串格式化使用 '%' 和 '{' 作为字符的正则表达式字符串

python - 如何使用 python 在文件中的搜索模式的下一行插入字符串?