我需要一个可能匹配日期的正则表达式。但是,天,月和年的分隔符可能会有所不同。可能是点,破折号,斜线...
我有的是
^([012]?[1-9]|3[01])[\\.\\-\\/\\\\](0?[1-9]|1[012])[\\.\\-\\/\\\\](19|20)\\d{2}$
所以是
([012]?[1-9]|3[01]) --the day part
(0?[1-9]|1[012]) --the month part
(19|20)\\d{2} --the year part
分隔符重复两次,根据我当前的表达式[\\.\\-\\/\\\\]
,可能会有所不同...我的意思是说,它匹配,例如:
01.01-1986
虽然我希望它仅在有两个点或两个破折号或两个分隔符允许的范围内时才匹配...所以上面给出的示例不应匹配。
我想可以用正则表达式的分组模式来完成。但是我不知道如何应用它。我也发现自己绝对不知道如何用谷歌搜索...
有人可以将我推向正确的方向吗?
PS:我最近看过SO正则表达式以匹配有效日期...就我而言,我确实知道它将与没有正则表达式的月份中的第31个匹配,并且所有月份都在2月缺席...全部好吧...
在Java中,我目前使用以下代码:
String value = "31/12/2086";
String pattern = ...
boolean result = value.matches(pattern);
在C#中
string value = "01.01.2014";
string pattern = "";
bool result = Regex.IsMatch(value, pattern);
如果有一种方法可以做我想做的事情,那么该解决方案对这两种语言都适用将会很棒。Java和C#正则表达式兼容吗?
您可以\\x
在正则表达式中使用x
组号。它表示由group匹配的相同字符串x
。因此,您可以使用类似
someRegex([.\\-/\\\\])someOtherRegex\\1anotherRegex
^^^^^^^^^^^ ^^^
group 1 here should appear same string as in group 1
例子
String regex = "someRegex([.\\-/\\\\])someOtherRegex\\1anotherRegex";
System.out.println("someRegex.someOtherRegex.anotherRegex".matches(regex));
System.out.println("someRegex.someOtherRegex-anotherRegex".matches(regex));
System.out.println("someRegex-someOtherRegex-anotherRegex".matches(regex));
输出:
true
false
true
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句