问题
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:
- Match a single character present in the list below
[A-Fa-f0-9?]+ - 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