Problem with brackets in regular expression in C#

本秂侑毒 提交于 2021-02-11 12:44:46

问题


can anybody help me with regular expression in C#? I want to create a pattern for this input:

{a? ab 12 ?? cd} 

This is my pattern:

([A-Fa-f0-9?]{2})+

The problem are the curly brackets. This doesn't work:

{(([A-Fa-f0-9?]{2})+)}

It just works for

{ab}

回答1:


I would use {([A-Fa-f0-9?]+|[^}]+)}

It captures 1 group which:

  1. Match a single character present in the list below [A-Fa-f0-9?]+
  2. Match a single character not present in the list below [^}]+



回答2:


If you allow leading/trailing whitespace within {...} string, the expression will look like

{(?:\s*([A-Fa-f0-9?]{2}))+\s*}

See this regex demo

If you only allow a single regular space only between the values inside {...} and no space after { and before }, you can use

{(?:([A-Fa-f0-9?]{2})(?: (?!}))?)+}

See this regex demo. Note this one is much stricter. Details:

  • { - a { char
  • (?:\s*([A-Fa-f0-9?]{2}))+ - one or more occurrences of
    • \s* - zero or more whitespaces
    • ([A-Fa-f0-9?]{2}) - Capturing group 1: two hex or ? chars
  • \s* - zero or more whitespaces
  • } - a } char.

See a C# demo:

var text = "{a? ab 12 ?? cd}";
var pattern = @"{(?:([A-Fa-f0-9?]{2})(?: (?!}))?)+}";
var result = Regex.Matches(text, pattern)
        .Cast<Match>()
        .Select(x => x.Groups[1].Captures.Cast<Capture>().Select(m => m.Value))
        .ToList();
foreach (var list in result)
    Console.WriteLine(string.Join("; ", list));
// => a?; ab; 12; ??; cd



回答3:


If you want to capture pairs of chars between the curly's, you can use a single capture group:

{([A-Fa-f0-9?]{2}(?: [A-Fa-f0-9?]{2})*)}

Explanation

  • { Match {
  • ( Capture group 1
    • [A-Fa-f0-9?]{2} Match 2 times any of the listed characters
    • (?: [A-Fa-f0-9?]{2})* Optionally repeat a space and again 2 of the listed characters
  • ) Close group 1
  • } Match }

Regex demo | C# demo

Example code

string pattern = @"{([A-Fa-f0-9?]{2}(?: [A-Fa-f0-9?]{2})*)}";
        string input = @"{a? ab 12 ?? cd}
{ab}";
        
foreach (Match m in Regex.Matches(input, pattern))
{
    Console.WriteLine(m.Groups[1].Value);
}

Output

a? ab 12 ?? cd
ab


来源:https://stackoverflow.com/questions/66024369/problem-with-brackets-in-regular-expression-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!