java 如何将此日期格式与正则表达式匹配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5986392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:51:19  来源:igfitidea点击:

How to match this date format with a regex?

javaregex

提问by MarkJ

hi to all regex master out there, I know you have a work around with regards to my problem. hehe

向所有正则表达式大师致敬,我知道您可以解决我的问题。呵呵

02-May-2011

or

或者

22-May-2011

or

或者

2-May-2011

(dd-MMM-yyyy) with yyyy not accepting any other characters than digit

(dd-MMM-yyyy) yyyy 不接受除数字以外的任何其他字符

回答by Town

[0-9]{1,2}/[a-zA-Z]{3}/[0-9]{4}

That's assuming that the month is a 3-letter version: eg, Jan, Feb, Mar.

假设月份是 3 个字母的版本:例如,Jan、Feb、Mar。

Updated version to match the changes to the question:

更新版本以匹配对问题的更改:

[0-9]{1,2}-[a-zA-Z]{3}-[0-9]{4}

As has been mentioned, this won't actually validate the date, it'll just validate that the string matches the format of: 1 or 2 numbers, a dash, 3 letters, a dash, 4 numbers.

如前所述,这实际上不会验证日期,它只会验证字符串是否与以下格式匹配:1 或 2 个数字、一个破折号、3 个字母、一个破折号、4 个数字

回答by Ry-

^\d{1,2}/[a-zA-Z]+/\d{4}$

Is probably what you're looking for. Although the technically correct one is:

大概就是你要找的。虽然技术上正确的是:

/^([12]\d|3[01])/(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|June?|July?|Aug(ust)?|Sep(t(ember)?)?|Oct(ober)?|Nov(ember)?|Dec(ember)?)/\d{4}$/i

Sorry for not validating February and the number of days in a month, but there are some things just not worth doing in regular expressions ;)

很抱歉没有验证二月和一个月的天数,但有些事情在正则表达式中不值得做;)

回答by Bhushan

Use SimpleDateFormat instead of using regexp. Read the tutorial at http://download.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.htmlfor more info.

使用 SimpleDateFormat 而不是使用正则表达式。阅读http://download.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html 上的教程了解更多信息。

回答by S34N

   /**
     * Created with IntelliJ IDEA.
     * User: S34N
     * Date: 2013/07/30
     * Time: 8:21 AM
     * To change this template use File | Settings | File Templates.
     */



    //Import the required classes/packages
    import javax.swing.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class dateInputScan {

        public static void main(String args[]) {

            dateInputScan run = new dateInputScan();
            run.dateInputScan();
        }

        public void dateInputScan() {

            //Instantiating variables
            String lvarStrDateOfTransaction = null;
            DateFormat formatter = null;
            Date lvarObjDateOfTransaction = null;

            //Use one of the following date formats.
            lvarStrDateOfTransaction = "29/07/2013";
            //lvarStrDateOfTransaction = "29-07-2013";
            //lvarStrDateOfTransaction = "20130729";
            //lvarStrDateOfTransaction = "2013-07-29";
            //lvarStrDateOfTransaction = "29/07/2013";

            //You can also add your own regex (Regular Expression)
            if (lvarStrDateOfTransaction.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})")) {
                formatter = new SimpleDateFormat("dd/MM/yyyy");
            } else if (lvarStrDateOfTransaction.matches("([0-9]{2})-([0-9]{2})-([0-9]{4})")) {
                formatter = new SimpleDateFormat("dd-MM-yyyy");
            } else if (lvarStrDateOfTransaction.matches("([0-9]{4})([0-9]{2})([0-9]{2})")) {
                formatter = new SimpleDateFormat("yyyyMMdd");
            } else if (lvarStrDateOfTransaction.matches("([0-9]{4})-([0-9]{2})-([0-9]{2})")) {
                formatter = new SimpleDateFormat("yyyy-MM-dd");
            } else if (lvarStrDateOfTransaction.matches("([0-9]{4})/([0-9]{2})/([0-9]{2})")) {
                formatter = new SimpleDateFormat("yyyy/MM/dd");
            }

            try {
                lvarObjDateOfTransaction = formatter.parse(lvarStrDateOfTransaction);
                JOptionPane.showMessageDialog(null, "Date: " + lvarObjDateOfTransaction);

            } catch (Exception ex) {    //Catch the Exception in case the format is not found.
                JOptionPane.showMessageDialog(null, ex);
            }
        }
    }

回答by Vladimir Stazhilov

Okay, here are almost all possible regex variations of the Date pattern:

好的,这里是日期模式的几乎所有可能的正则表达式变体:

private final static Pattern DATE_PATTERN_1 = 

        Pattern.compile (
            "(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat) " + 
            "(?:Jan|Feb|Mar|Apr|May|June?|July?|Aug|Sept?|Oct|Nov|Dec) " + 
            "\d\d \d\d:\d\d:\d\d \S+ \d\d\d\d", Pattern.CASE_INSENSITIVE);

private final static Pattern DATE_PATTERN_2 = 
        Pattern.compile (
            "\d{4}.\d{2}.\d{2}", Pattern.CASE_INSENSITIVE);

private final static Pattern DATE_PATTERN_3 = 
        Pattern.compile (
            "\d{2}.\d{2}.\d{4}", Pattern.CASE_INSENSITIVE);

private final static Pattern DATE_PATTERN_4 = 
        Pattern.compile (
            "([0-9]{4})([0-9]{2})([0-9]{2})", Pattern.CASE_INSENSITIVE);        

private final static Pattern DATE_PATTERN_5 = 
        Pattern.compile (
            "^([12]\d|3[01]).(Jan(uary)?|Feb(ruary)?|Mar(ch)?|Apr(il)?|May|June?|July?|Aug(ust)?|Sep(t(ember)?)?|Oct(ober)?|Nov(ember)?|Dec(ember)?).\d{4})$", Pattern.CASE_INSENSITIVE); 

Please note that "." character stand for any char.

请注意“。” 字符代表任何字符。

回答by Mukesh K

Since it is date, which you are trying to find a match, using SimpleDateFormat instead of a regex based match check should be the appropriate solution. Hopefully, the below snippet should do the job.

由于它是日期,您正在尝试查找匹配项,因此使用 SimpleDateFormat 而不是基于正则表达式的匹配检查应该是合适的解决方案。希望下面的代码片段可以完成这项工作。

public static boolean dateFormatValidate(String strDate,String dateFormat)
{
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    String strParsed = null;
    Date parsed =null;

    try
    {
        parsed = formatter.parse(strDate);
        strParsed = formatter.format(parsed);
    }
    catch (ParseException e)
    {
        MYLogger.logger.info(e.getMessage());
    }

    return strDate.equals(strParsed);
}