[英]Parsing values from a formatted string in C#
如何從C#中的格式化字符串中解析多個值?
字符串的格式為:“blah blah blah(foo:this,bar:that)”
我需要解析foo
和bar
值。 括號總是在行的末尾。
編輯:對不起......那不是很清楚。 我的意思是我需要知道“foo”值和“bar”值,以便我可以說,在其他地方,“foo就是這個”,“bar就是那個”。
謝謝
編輯:在OP澄清后更新。
這應該做:
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]);
}
}
這輸出:
如果您需要確保匹配僅發生在字符串的末尾,而不是匹配字符串中其他位置的類似格式化值,請將$
添加到模式的末尾:
string pattern = @"\((?:(?<Values>.*?:[^,\s]+)[,\s]*)+\)$";
正則表達式不應該用於解析,如果可能的話,只有lexing。 將lexed標記傳遞給有限狀態機進行實際解析。
我在這里基於你的問題做了很多假設,但這應該讓你朝着正確的方向前進。
#!/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'
至於.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。
解析表達式基於您發布的示例,因此它會跳過所有內容(
然后開始解析值。請注意(?:..)
是非捕獲組,因此它不會出現在結果中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.