[英]Why my regex isn't working for date?
使用正則表達式來匹配字符串中的日期時遇到問題。 實際上,我有很多可以匹配的“日期格式”,但是第一個格式不起作用,我也不知道為什么它不起作用...
格式類似於“ 2013年9月12日”或“ 2014年5月6日”或“ 2014年6月2日” ...
在我的字符串文本中 ,有以下日期:“ 2014年7月4日”。
這是我的代碼:
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));
但是涉及到此錯誤:
Exception in thread "main" java.lang.IllegalStateException: No match found
我什至嘗試使用較小的正則表達式,但仍然不匹配任何東西。
預先感謝您的幫助!
您需要檢查if(m.find())
並打印m.group(0)
因為如果您打印m.group(1)
則將根據您的輸入打印1或2 (1|2)
作為輸入在2014年, m.group(1)
將打印m.group(0)
表示"[a-zA-Z]+ [0-3]?[0-9], (1|2)\\\\d{3}"
,它會打印您的全文,因為它將您的完整正則表達式作為第一組,因為除了(1|2)
之外沒有其他組。
試試這個代碼。
String text="July 4, 2014";
Pattern p = Pattern.compile("[a-zA-Z]+ [0-3]?[0-9], (1|2)\\d{3}", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(text);
if (m.find( )) {
System.out.println(m.group(0));
}else{
System.out.println("No match found");
}
產量
2014年7月4日
請訪問這里以了解基本示例
您需要條件m.find()並打印m.group(0)代替(1)。
String text = "July 4, 2014";
String pattern = "\\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(Nov|Dec)(?:ember)?)\\D [0-9]{1,2}, [0-9]{4}";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(text);
if(m.find()){
System.out.println("Found value: " + m.group(0));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.