使用正则表达式(.net)的字符串中的值

时间:2011-06-13 15:23:01

标签: .net regex

我正在尝试获取值

Title: some, song title
Length: 5:35
Rating: 0
Genre: Other
Size: 7.6 MB

来自一个字符串,但我需要它,所以它们可以放在字符串中的任何位置,例如..

Title: some, song title, Length: 5:35, Rating: 0, Genre: Other, Size: 7.6 MB
Size: 7.6 MB, Title: some, song title, Length: 5:35, Genre: Other, Rating: 0

两者都会返回上面的值

由于

5 个答案:

答案 0 :(得分:3)

对于解析器来说,这比Regex更重要。你可以在它的空间上拆分字符串,然后循环查找冒号并计算那是什么值。在这里使用正则表达式要么效率低下,要么让你发疯。

答案 1 :(得分:3)

嗯,你可以这样做:

/Title: (.*?)(?=,\s\w+:|$)/               Song Title
/Length: (\d+:\d+)/                       Length
/Rating: (\d+)/                           Rating
/Genre: (.*?)(?=,\s\w+:|$)/               Genre
/Size: (\d+(?:\.\d)?+\s\w+)/              Size

(?=,\s\w+:|$)模式只是确保它只抓取“字段”的值(即在行尾或下一个分组处停止)。

答案 2 :(得分:2)

您是否能够控制输入字符串的格式?如果是这样,那么将其更改为:

Title: some, song title; Length: 5:35; Rating: 0;

使用;而不是,。您可以拆分字符串:

string[] parts = input.Split(';');

单独使用这些部件。在这种情况下,不要浪费你的正则表达式。

答案 3 :(得分:0)

我不会使用正则表达式而是

string input = 
    "Title: some, song title; Length: 5:35; Rating: 0; Genre: Other; Size: 7.6 MB";

var values = input.Split(new[] { "; " }, StringSplitOptions.None)
    .Select(v => v.Split(new[] { ": " }, StringSplitOptions.None))
    .ToDictionary(v => v[0], v => v[1]);

我不得不将分隔符更改为分号而不是逗号。

答案 4 :(得分:0)

这是没有正则表达式的一种方法:

dim inputs = {"Title: some, song title, Length: 5:35, Rating: 0, Genre: Other, Size: 7.6 MB", 
              "Size: 7.6 MB, Title: some, song title, Length: 5:35, Genre: Other, Rating: 0" }

for each s in inputs
    dim output as new dictionary(of string, string)
    dim tokens = s.split(", ")
    dim lastKey = ""
    for each t in tokens
        if t.contains(":") then
            dim kv = t.split(":")
            lastKey = kv(0).trim
            output.add(lastkey, "")
            for n = 1 to kv.length - 1
                output(lastkey) &= kv(n) & if( n = kv.length -1, "", ":")
            next n              
        else
            output(lastkey) &= ", " & t.trim
        end if
    next t
next s

如果您的密钥包含":",则会中断。