为什么我的正则表达式不工作日期? [英] Why my regex isn't working for date?

查看:152
本文介绍了为什么我的正则表达式不工作日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用正则表达式匹配字符串中的日期时出现问题。其实我有很多日期格式匹配,但第一个不起作用,我不明白为什么它不会工作...



格式如2013年9月12日或2014年5月6日或2014年6月2日...



在我的字符串



以下是我的代码:



模式p = Pattern.compile([a-zA-Z] + [0-3]?[0-9],(1 | 2)\\\d {3},Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
System.out.println(m.group(1));

但是出现这个错误:

 线程中的异常mainjava.lang.IllegalStateException:找不到匹配

我甚至尝试使用较小的正则表达式,但仍然不符合任何条件。



提前谢谢您的帮助!

解决方案

您需要调用 Matcher#find() Matcher#matches )在调用 Matcher#group 之前。



否则,不执行匹配,因此,您既没有整个组,也没有任何一个反向引用的填充。



上述两种方法都返回 boolean ,这将帮助您推断您所需的组是否包含任何文本。



一个典型的成语是:

  if(matcher.find ()){
//获取组
}

文档此处



另一方面,我建议您使用 DateFormat 而不是日期的正则表达式 - API 这里


I've got a problem using a regex to match the date in a string. Actually I've got a lot of "date formats" to match but the first one doesn't work and I don't get why it wouldn't work...

The format is like "September 12, 2013" or "May 6, 2014" or "June 02, 2014"...

In my string text, there is the following date : "July 4, 2014".

Here's my code :

Pattern p = Pattern.compile("[a-zA-Z]+ [0-3]?[0-9], (1|2)\\d{3}", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
System.out.println(m.group(1));

But it comes to this error :

Exception in thread "main" java.lang.IllegalStateException: No match found

I even tried with smaller regex but it still doesn't match anything.

Thank you in advance for the help !

解决方案

You need to invoke Matcher#find() or Matcher#matches() before invoking Matcher#group.

Otherwise, the match is not performed, hence you have neither the whole group, nor any single back-references populated.

Both methods mentioned above return boolean, which will help you infer whether or not your desired group will contain any text.

A typical idiom would be:

if (matcher.find()) {
    // get the group(s)
}

Documentation here.

On the other hand, I would recommend you use DateFormats instead of regular expressions for dates - API here.

这篇关于为什么我的正则表达式不工作日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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