![](/img/trans.png)
[英]Regular expression to extract Date value specified in word from the string in Java
[英]Using regular expression in Java to extract date from string in the format 01OCT12 14:26
我正在從文件或字符串中讀取日期,格式為01OCT12 14:26
我知道日期將是OCT或11月,這可能有助於我編寫更精確的正則表達式。
我已經讀過Java提供的許多使用正則表達式的選項,例如Matcher&Pattern以及Scanner類,希望能找到幫助解決該問題的最簡潔方法。
如果您知道日期在字符串中的何處,則可以使用SimpleDateFormat
進行解析,而不要使用正則表達式:
DateFormat dateFormat = new SimpleDateFormat("yyMMMdd kk:mm", Locale.ENGLISH);
Date result = df.parse(stringDate);
(我假設01
是年, 12
是天,但是如果將其取反,則需要將日期格式字符串中的yy
和dd
反。)
下面是使用正則表達式的示例:
String example = "01OCT12 14:26";
String pattern = "^(\\d{2})(?:OCT|NOV)(\\d{2}) (\\d{1,2}):(\\d{2})$";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(example);
if (m.find())
{
//prints example
System.out.println(m.group());
System.out.println(m.group(1)); //prints 01
System.out.println(m.group(2)); //prints 12
System.out.println(m.group(3)); //prints 14
System.out.println(m.group(4)); //prints 26
}
"^(\\\\d{2})(?:OCT|NOV)(\\\\d{2}) (\\\\d{1,2}):(\\\\d{2})$"
細分:
^
表示從 (...)
是一個捕獲組,表示...
是您要捕獲的模式
\\\\d{2}
,表示[0-9]
中任意數字的兩位 (?:OCT|NOV)
?:
表示不捕獲以下內容 OCT|NOV
手段必須是OCT或NOV (\\\\d{1,2})
是與1或2個數字[0-9]
匹配的捕獲組 $
表示以 您可能不希望使用正則表達式來完成此任務。 盡管如此,我相信這就是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.