Java regular expression extracts the date implementation code from the string

Source: Internet
Author: User
Tags regular expression

You may need to extract or filter the date or time from a String or text. You can use the following program:

The code is as follows: Copy code

Public String run (String text ){
String dateStr = text. replaceAll ("r? N ","");
DateStr = dateStr. replaceAll ("\ s + ","");
       
Try {
           
List matches = null;
Pattern p = Pattern. compile ("(\ d {} [-| \/] \ d {} [-| \/] \ d }: \ d {1, 2 }:\ d {1, 2}) ", Pattern. CASE_INSENSITIVE | Pattern. MULTILINE );
Matcher = p. matcher (dateStr );
If (matcher. find () & matcher. groupCount ()> = 1 ){
Matches = new ArrayList ();
For (int I = 1; I <= matcher. groupCount (); I ++ ){
String temp = matcher. group (I );
Matches. add (temp );
                }
} Else {
Matches = Collections. EMPTY_LIST;
            }           
           
If (matches. size ()> 0 ){
Return (String) matches. get (0). trim ();
} Else {
Return "";
            }
           
} Catch (Exception e ){
Return "";
        }
    }

The current function of this program is to extract from the string in the form of "yyyy-MM-dd HH: mm: ss" or "yyyy/MM/dd HH: mm: ss. If the time format is short, it cannot be processed, but it can be easily expanded.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.