为什么我的正则表达式不工作日期? [英] Why my regex isn't working for date?
问题描述
我使用正则表达式匹配字符串中的日期时出现问题。其实我有很多日期格式匹配,但第一个不起作用,我不明白为什么它不会工作...
格式如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 DateFormat
s instead of regular expressions for dates - API here.
这篇关于为什么我的正则表达式不工作日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!