Extracting movie name and year from string were year is optional

本小妞迷上赌 提交于 2019-12-23 04:52:53

问题


I'm missing a really obvious thing here, but I'm new to regex so be kind ;-)

I have a number of films in an arbitrary format that may or may not have the year attached.

My Movie Name 2010
Some.Other.Super.Cool.Movie
The~Third|Movie.2010

Now, using (.+)\W(\d{4}) I can extract the two movies with dates into two groups one containing the name and the other the year, but the middle one gets ignored? I'm just a little unsure on how to actually make the year segment optional.

Ideally, ;-), I could use a single expression to return the names with \W converted into spaces but that a different conversation.

Thanks in advance


回答1:


using a ? after the a character group will make it optional so in your case after the (\d{4})

(.+)\W(\d{4})?

That is because you are using greedy matching on (.+) and \W includes the new line character in it's set ( I think it does at least ). Strip your string of trailing whitespace and if that doesn't work make (.+) lazy with a ? of it's own, (.+?) - Also consider that \W may be the wrong delimiter for this problem.

Also adding $ to the end may help, as that would require the digits to end the function is they can, try lazing matching and $.

(.+?)\W(\d{4})?$



回答2:


? Makes it optional

(.+?)\W?(\d{4})?$


来源:https://stackoverflow.com/questions/5400425/extracting-movie-name-and-year-from-string-were-year-is-optional

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!