从弦中获取年份(例如Rogue Assassin 2007)

时间:2012-12-28 05:41:57

标签: .net regex vb.net string

我似乎无法弄清楚如何从Rogue Assassin 2007说出来并返回:

moviename = "Rogue Assassin" 'Whitespace doesn't matter
movieyear = "2007" 'Whitespace doesn't matter

然而,我无法让它发挥作用。我一直在尝试以下方法:

    If System.Text.RegularExpressions.Regex.IsMatch(fn, "[0-9][0-9][0-9][0-9]") Then 'Is this right?
        Dim mtemp As String() = fn.Split(" ") 'Movie temp array
        myear(0) = mtemp.Last 'Attempting to set year to the last split
        For Each z As String In mtemp 'Adding the other elements in mtemp together to remake the title
            If z IsNot mtemp.Last Then
                mtitle(0) = z & " " 'Movie title
            Else
                Exit For
            End If
        Next
        ...
    Else
        ...
    End If

任何帮助都非常感谢!

2 个答案:

答案 0 :(得分:2)

你可以尝试

Dim r As Regex = new Regex("(.*)\s+([0-9]+)$");
Dim match As Match = System.Text.RegularExpressions.Regex.Match("Rogue Assassin 2007")

上面的代码会将匹配捕获为2组,然后您可以使用match.Groups(1).Captures(0).Value和match.Groups(1).Captures(1).Value

http://msdn.microsoft.com/en-us/library/twcw2f1c.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2

答案 1 :(得分:2)

1) Regular expression for matching year strings containing year 1800 to 2013 (ideal regex for obtaining movie year from the title)

1[89][0-9]{2}|200[0-9]|201[0-3]

2) Regular expression for matching year strings containing year from 1800 onwards.

1[89][0-9]{2}|20[0-9]{2}

Have tested the pattern (1) for the below movie titles:

Die Hard 2 1990 -> 1990
Django Unchained (2012) -> 2012
This Is 40 (2012) -> 2012
The Twilight Saga: Breaking Dawn - Part 2 - 2012 -> 2012
Die Hard 4.0 2007 -> 2007

假设:

由于您的问题中未指定年份格式,因此假设年份始终为4位数。

电影片名也可以包含其他4位数字,因此年份特别匹配从1800年到2013年[可以获得大多数电影片名的年份​​值,这可以减少匹配的垃圾数据。考虑到这是为了满足您现在的需求:)]。