简体   繁体   English

如何使用正则表达式提取带有多个花括号的字符串?

[英]How to use regex to extract a string with multiple curly braces?

I have this sample string我有这个示例字符串

`{1:}{2:}{3:}{4:\r\n-}{5:}`

and I want to extract out only {4:\\r\\n-}我只想提取{4:\\r\\n-}

This is my code but it is not working.这是我的代码,但它不起作用。

var str = "{1:}{2:}{3:}{4:\r\n-}{5:}";
var regex = new Regex(@"{4:*.*-}");
var match = regex.Match(str);

You need to escape the special regex characters (in this case the opening and closing braces and the backslashes) in the search string.您需要转义搜索字符串中的特殊正则表达式字符(在本例中为左大括号和反斜杠)。 This would capture just that part:这将只捕获那部分:

var regex = new Regex("\{4:\\r\\n-\}");

... or if you wanted anything up to and including the slash before the closing brace (which is what it looks like you might be trying to do)... ...或者如果您想要任何内容​​,包括右括号之前的斜线(这看起来像是您可能正在尝试做的)...

var regex = new Regex("\{4:[^-]*-\}");

You just need to escape your \\r and \\n characters in your regular expression.你只需要在你的正则表达式中转义你的\\r\\n字符。 You can use the Regex.Escape() method to escape characters in your regex string which returns a string of characters that are converted to their escaped form.您可以使用Regex.Escape()方法来转义正则表达式字符串中的字符,该字符串会返回转换为转义形式的字符串。

Working example: https://dotnetfiddle.net/6GLZrl工作示例: https ://dotnetfiddle.net/6GLZrl

using System;
using System.Text.RegularExpressions;
                
public class Program
{
    public static void Main()
    {
        string str = @"{1:}{2:}{3:}{4:\r\n-}{5:}";
        string regex = @"{4:\r\n-}";  //Original regex
        Match m = Regex.Match(str, Regex.Escape(regex));
        if (m.Success)
        {
            Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index);        
        }
        else
        {
            Console.WriteLine("No match found");        
        }
    }
} 

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

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