从日期正则表达式中提取月,日和年 [英] Extract month, day and year from date regex

查看:938
本文介绍了从日期正则表达式中提取月,日和年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的日期为mm / dd / yyyy格式。但是,根据什么日期或月份,不能保证mm / dd部分必须有两位数。所以日期可能是:

I have a date in "mm/dd/yyyy" format. But, depending on what day or month, there is no guarantee that the "mm/dd" part will necessarily have two digits. So the dates may be:

11/12/2014

6/12/2014

11/5/2014

在上述所有情况中,我需要能够提取<的每个值code> mm , dd yyyy 所以我可以做类似的事情这是一个计算:

In all of the above situations I will need to be able to extract each value for mm, dd, and yyyy so I can do something like this for a calculation:

Month = regex that returns month part.
Day = regex that returns day part
Year = regex that returns 4 digits year part.

\d {2} / \d {2} / \d {2} 匹配整个事情。

推荐答案

Regexp解决方案



匹配所有日期的正确正则表达式是: \d {1,2} / \d {1,2} / \d {4} 。符号
{n,m} 称为限制重复,在本例中为 \d {n, m} 表示在n和m位数之间(包括)。您可以在此处详细了解:限制重复

Regexp Solution

The proper regex matching all of your dates is: \d{1,2}/\d{1,2}/\d{4}. Notation {n,m} is called limiting repetition and in this case \d{n,m} means "between n and m digits (inclusive)". You can read more about that here: Limiting Repetition.

如果要创建匹配组,请使用(和)(括号)。另外,在JavaScript中,您必须使用 \ 转义 / ,因此您的正则表达式为: /(\d {1,2})\ /(\d {1,2})\ /(\d {4})/

If you want to create matching groups, use "(" and ")" (parentheses). Addiitonally, in JavaScript, you have to to escape / with \ and thus your regexp is: /(\d{1,2})\/(\d{1,2})\/(\d{4})/

您可以使用正则表达式的 exec 函数来匹配字符串。它返回一个数组,其中包含匹配的文本作为第一个元素,然后返回每个匹配组的一个项目。

You can use exec function of the regexp to match strings against it. It returns an array containing the matched text as the first element and then one item for each of the matched groups.

您可以在MDN上找到更多信息 RegExp.prototype.exec 或参见下面的示例:

You can find out more on MDN RegExp.prototype.exec or see this example below:

const datePattern = /(\d{1,2})\/(\d{1,2})\/(\d{4})/;
const date = datePattern.exec("11/12/2014"); // ["11/12/2014", "11", "12", "2014"]

注意:如果传递的字符串无效(与正则表达式不匹配) exec 函数将返回 null 。这是对用户输入或数据进行简要验证的简单方法。

Note: If an invalid string is passed (not matching the regular expression) exec function will return null. It's an easy way to do brief validation of users' input or data.

或者你可以只需拆分字符串:

Alternatively you can simply split the strings:

"11/12/2014".split('/'); // ["11", "12", "2014"]

但这无论如何都可行字符串实际包含的内容(它可能包含字符串ba / tm / an并且split仍将返回包含三个元素的数组)。因此,如果要验证日期,Regexp可能更适合。

But this will work regardless of what the string actually contains (it might contain string "ba/tm/an" and split will still return an array with three elements). For this reason, Regexp is probably a better fit if you want to validate the dates.

这篇关于从日期正则表达式中提取月,日和年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆