开发者

Extracting movie name and year from string were year is optional

开发者 https://www.devze.com 2023-02-18 08:25 出处:网络
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.

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


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})?$


? Makes it optional

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

精彩评论

暂无评论...
验证码 换一张
取 消