【问题标题】:Get Year from String (e.g. Rogue Assassin 2007)从字符串中获取年份(例如 Rogue Assassin 2007)
【发布时间】:2012-12-28 05:41:57
【问题描述】:

我似乎不知道如何从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

非常感谢任何帮助!

【问题讨论】:

  • 你总是保证名字中有年份吗?年份总是四个字符还是两个字符?您是否能够预先格式化年份值以使其更易于识别?
  • 这只是大约 5 个 if 语句的一部分...前 2 个是大括号中的年份,方括号中的年份,然后是这个,然后如果年份是目录名称,那么最后,仅搜索标题。

标签: .net regex vb.net string


【解决方案1】:
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 年特别匹配年份 [这可以从大多数电影标题中获取年份值,这减少了匹配的垃圾数据。考虑一下这是为了满足您现在的需求:)]。

【讨论】:

    【解决方案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

    【讨论】:

    • 这有一个小问题,因为它可以匹配可能不是日期的数字标记,例如标题“Beverly Hills 90215”的 90215。
    • 我不是正则表达式...您的正则表达式是否适用于“虎胆龙威 2 1990”?
    • 它不适用于“虎胆龙威 2 1990”,但它适用于“(.*)\s+([0-9]+)$”
    • 那么...人们推荐哪种表达方式? ".*\s+([0-9]+)$""(\w+)\s+([0-9]+)"
    • \w 还有其他问题。它不包含空格,因此您将返回“刺客”作为第一个捕获组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 2021-05-10
    相关资源
    最近更新 更多