任意长度的正则表达式 - 正整数和负整数以及java中的长整数

时间:2015-06-05 08:34:22

标签: java regex

我希望像20140101一样传递日期,因为它的数据类型在元文件中是整数,所以我尝试了很多正则表达式,但它总是返回false。另一列类型为long的列,其数据类似于0000000000000。那么integerlong的正则表达式是分开的。谢谢

2 个答案:

答案 0 :(得分:0)

我想像这样的正则表达式应该适用于整数:

(\d{4})(\d{2})(\d{2})

EXAMPLE

假设您的日期占据了长期的最后一位数字,那么您应该使用正则表达式:

\d{5}(\d{4})(\d{2})(\d{2})

EXAMPLE

在Java中,您应该能够获得所寻找的日期对象:

    String toParse = "20140102";
    Pattern pattern = Pattern.compile("(\\d{4})(\\d{2})(\\d{2})");
    Matcher matcher = pattern.matcher(toParse);
    if (matcher.find()) {
        int year = Integer.parseInt(matcher.group(1));
        int month = Integer.parseInt(matcher.group(2));
        int day = Integer.parseInt(matcher.group(3));

        System.out.println(new Date(year - 1900, month - 1, day));
    }

您可以尝试HERE

答案 1 :(得分:-2)

如果您有像20140101这样的字符串,并且必须使用正则表达式进行测试,则可以使用此正则表达式:

/ [0-9] {8} /

示例:

import java.util.regex.Pattern; import java.util.regex.Matcher;

公共类MatcherExample {

public static void main(String[] args) {

    String text    =
        "This is the text to be searched " +
        "for occurrences of the http:// pattern.";

    String patternString = "/[0-9]{8}/";

    Pattern pattern = Pattern.compile(patternString);

    Matcher matcher = pattern.matcher(text);
    boolean matches = matcher.matches();
}

}

您可以使用https://regex101.com/来测试正则表达式。

相关问题