首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从字符串中获取年份(例如Rogue Assassin 2007)

从字符串中获取年份(例如Rogue Assassin 2007)
EN

Stack Overflow用户
提问于 2012-12-28 13:41:57
回答 2查看 181关注 0票数 1

我似乎想不出如何从Rogue Assassin 2007那里获取年份并返回:

代码语言:javascript
复制
moviename = "Rogue Assassin" 'Whitespace doesn't matter
movieyear = "2007" 'Whitespace doesn't matter

然而,我不能让它工作。我一直在尝试以下几种方法:

代码语言:javascript
复制
    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

非常感谢您的帮助!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-28 14:39:48

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2012-12-28 13:47:08

你可以试试

代码语言:javascript
复制
Dim r As Regex = new Regex("(.*)\s+([0-9]+)$");
Dim match As Match = System.Text.RegularExpressions.Regex.Match("Rogue Assassin 2007")

上面的代码会将匹配结果捕获到两组中,然后您可以使用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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14065106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档