Parsing values ​​from a formatted string in C #

How can I parse multiple values ​​from a formatted string in C #?

The string is in this format: "blah blah blah (foo: this, bar: that)"

I need to analyze the values ​​of fooand bar. The brackets are always at the end of the line.

Edit: Sorry ... that was not very clear. I meant that I need to know the value of "foo" and the value of "bar", so that I can say, somewhere else, "foo is this" and "bar is that".

thank

+3
source share
4 answers

EDIT: updated after clarification of the OP.

This should do:

string input = "blah blah blah (foo:this, bar:that,1:one,2:two)";
string pattern = @"\((?:(?<Values>.*?:[^,\s]+)[,\s]*)+\)";
foreach (Match m in Regex.Matches(input, pattern))
{
    foreach (Capture c in m.Groups["Values"].Captures)
    {
        string[] values = c.Value.Split(':');
        Console.WriteLine("{0} : {1}", values[0], values[1]);
    }
}

:

  • foo: this
  • bar:
  • 1: one
  • 2: two

, , , $ :

string pattern = @"\((?:(?<Values>.*?:[^,\s]+)[,\s]*)+\)$";
+1

, , . .

0

, , .

#!/usr/bin/perl

my $input = "blah blah blah (foo:this, bar:that, foo2:150)";

my @ray = ($input =~ /.*?:(\w*)/g);
foreach $x (@ray)
{
    print "Value: '$x'\n";
}

:

Value: 'this'
Value: 'that'
Value: '150'
0

.NET, :

> $s = "blah blah blah (foo:this, bar:that)"
> $result = [regex]::Match($s, '[^(]*\((?:\w+:(?<t>\w+),\s*)*\w+:(?<t>\w+)\)$')
> $result.Groups

Groups   : {blah blah blah (foo:this, bar:that), that}
Success  : True
Captures : {blah blah blah (foo:this, bar:that)}
Index    : 0
Length   : 35
Value    : blah blah blah (foo:this, bar:that)

Success  : True
Captures : {this, that}
Index    : 30
Length   : 4
Value    : that

> $result.Groups[1].captures
Index                                          Length Value
-----                                          ------ -----
20                                               4 this
30                                               4 that

PowerShell. PowreShell .NET, .NET.

The parsing expression is based on the example you posted, so it skips everything to (and then starts parsing the values. Please note that this (?:..)is a non-capturing group, so it does not appear in the results.

0
source

Source: https://habr.com/ru/post/1731197/


All Articles