简体   繁体   中英

Using regular expression in Java to extract date from string in the format 01OCT12 14:26

I am looking to read dates from either a file or String in the format 01OCT12 14:26

I know the dates will be of either the month OCT or NOV which may help me write a more precise regex expression.

I have read of quite a few option Java provides for using regex such as Matcher & Pattern and also the Scanner class and was hoping for help to find the cleanest way of tackling this.

If you know where in the string the date is, you could use a SimpleDateFormat for parsing instead of using a regex:

DateFormat dateFormat = new SimpleDateFormat("yyMMMdd kk:mm", Locale.ENGLISH);
Date result = df.parse(stringDate);  

(I assumed that 01 was the year and 12 was the day, but if it's reversed, then you would need to reverse the yy and dd in the date format string.)

Here's how to do it with regular expressions, with an example:

        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})$" breakdown:

  • ^ means begins with
  • (...) is a capturing group, meaning that ... is a pattern that you want to capture
    • In this case, the pattern is \\\\d{2} , which means two of any digit in [0-9]
  • (?:OCT|NOV)
    • ?: means do NOT capture the following
    • OCT|NOV means must be either OCT or NOV
  • (\\\\d{1,2}) is a capture group that matches 1 or 2 numbers [0-9]
  • Finally, $ means ends with

You may not want to use regular expressions to accomplish this task; nonetheless, I believe that this is what you were looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM