如何修复日期正则表达式?

huangapple go评论90阅读模式
英文:

how to fix the date regex?

问题

我试图仅使用正则表达式匹配`dd/MM/yyyy`日期格式但如果我输入`dd/MM/yy`它也会被接受我想知道如何使其只接受`dd/MM/yyyy`格式的值

如果我使用

```Java
new SimpleDateFormat("dd/MM/yyyy").parse(value);

代码仍然会接受dd/MM/yy格式。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String value = "10/02/20";

        Pattern pattern = Pattern.compile("^([0-2][0-9]||3[0-1])/(0[0-9]||1[0-2])/([0-9][0-9])?[0-9][0-9]$");

        Matcher matcher = pattern.matcher(value);

        System.out.println(matcher.find());
    }
}

<details>
<summary>英文:</summary>

I&#39;m trying to use the regex only for the `dd/MM/yyyy` date format but if I enter the `dd/MM/yy` value it accepts. I would like to know how to make it accept only the `dd/MM/yyyy` values.

If I use 

```Java
new SimpleDateFormat(&quot;dd/MM/yyyy&quot;).parse(value); 

the code continues to accept dd/MM/yy format.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
    
public class Main {
    public static void main(String[] args) {
    	String value = &quot;10/02/20&quot;;
    	     	    
   		Pattern pattern = Pattern.compile(&quot;^([0-2][0-9]||3[0-1])/(0[0-9]||1[0-2])/([0-9][0-9])?[0-9][0-9]$&quot;);
    					
    	Matcher matcher = pattern.matcher(value);
    		
    	System.out.println(matcher.find());
   	}
}

答案1

得分: 1

我建议您从过时且容易出错的 java.util 日期时间 API 和 SimpleDateFormat 切换到现代的 java.time 日期时间 API 和相应的格式化 API(包名为 java.time.format)。从 Trail: Date Time 了解更多关于现代日期时间 API 的信息。

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 定义格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

        String dateString;
        LocalDate date = null;
        boolean valid;

        do {
            valid = true;
            System.out.print("输入格式为 dd/MM/yyyy 的日期:");
            dateString = scanner.nextLine();
            try {
                // 尝试解析输入字符串
                date = LocalDate.parse(dateString, formatter);
            } catch (DateTimeParseException e) {
                System.out.println("无效格式");
                // 异常时将 `valid` 设置为 false
                valid = false;
            }
        } while (!valid); // 只要 valid 为 false 就循环

        System.out.println("以 ISO-8601 格式的日期:" + date);
        System.out.println("以 dd/MM/yyyy 格式的日期:" + date.format(formatter));
    }
}

示例运行:

输入格式为 dd/MM/yyyy 的日期:09/09/20
无效格式
输入格式为 dd/MM/yyyy 的日期:09/09/2020
以 ISO-8601 格式的日期:2020-09-09
以 dd/MM/yyyy 格式的日期:09/09/2020

正则表达式解决方案:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String dateString;
        boolean valid;
        do {
            valid = true;
            System.out.print("输入格式为 dd/MM/yyyy 的日期:");
            dateString = scanner.nextLine();
            if (!dateString.matches("\\d{2}/\\d{2}/\\d{4}")) {
                System.out.println("无效格式");
                valid = false;
            }
        } while (!valid); // 只要 valid 为 false 就循环
        System.out.println(dateString);
    }
}

示例运行:

输入格式为 dd/MM/yyyy 的日期:09/09/20
无效格式
输入格式为 dd/MM/yyyy 的日期:09/09/2020
09/09/2020

正则表达式解释:

  1. \d 表示数字
  2. X{n} 表示 X 恰好出现 n
英文:

I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		// Define the format
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;dd/MM/yyyy&quot;);

		String dateString;
		LocalDate date = null;
		boolean valid;

		do {
			valid = true;
			System.out.print(&quot;Enter a date in dd/MM/yyyy format: &quot;);
			dateString = scanner.nextLine();
			try {
				// Try to parse the input string
				date = LocalDate.parse(dateString, formatter);
			} catch (DateTimeParseException e) {
				System.out.println(&quot;Invalid format&quot;);
				// Set `valid` to false in case of exception
				valid = false;
			}
		} while (!valid);// Loop as long as valid is false

		System.out.println(&quot;Date in ISO-8601 format: &quot; + date);
		System.out.println(&quot;Date in dd/MM/yyyy format: &quot; + date.format(formatter));
	}
}

A sample run:

Enter a date in dd/MM/yyyy format: 09/09/20
Invalid format
Enter a date in dd/MM/yyyy format: 09/09/2020
Date in ISO-8601 format: 2020-09-09
Date in dd/MM/yyyy format: 09/09/2020

Regex Solution:

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String dateString;
		boolean valid;
		do {
			valid = true;
			System.out.print(&quot;Enter a date in dd/MM/yyyy format: &quot;);
			dateString = scanner.nextLine();
			if (!dateString.matches(&quot;\\d{2}\\/\\d{2}\\/\\d{4}&quot;)) {
				System.out.println(&quot;Invalid format&quot;);
				valid = false;
			}
		} while (!valid);// Loop as long as valid is false
		System.out.println(dateString);
	}
}

A sample run:

Enter a date in dd/MM/yyyy format: 09/09/20
Invalid format
Enter a date in dd/MM/yyyy format: 09/09/2020
09/09/2020

Explanation of the regex:

  1. \d specifies a digit
  2. X{n} speciifies X, exactly n times

huangapple
  • 本文由 发表于 2020年9月9日 19:46:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63811019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定