【问题标题】:Extract timestamp from the middle of a line in text file从文本文件中的一行中间提取时间戳
【发布时间】:2021-07-19 15:53:53
【问题描述】:

我正在尝试读取一个包含不同信息的文本文件。文本文件的一部分包含我需要的以下信息

### Size: 280
### file data: 
### Scenario: - timestamp: 1620832134319 - Wed May 12 17:08:54 CEST 2021
### It needed to compare later timestamp: 1620832134319 - Wed May 12 17:08:54 CEST 2021

我正在尝试提取此时间戳“1620832134319”或“Wed May 12 17:08:54”。然后我需要在未来增加 10 天。并比较原始时间戳和未来10天的时间戳是否相同。

有人可以在这种情况下帮助我或指导我吗?直到现在我都试图打开文件,但读取和提取时间戳并添加更多部分是我真正陷入困境的地方。

public class readTimeStampTest
{

static String filePath = "c:/timestamp.txt";
long timestamp10daysinfuture = 1621868934;

public static void getTimeStamp()
{
    System.out.println("timestamp test... " );
    File file = new File(filePath);
    FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);
    String line;
    while((line = br.readLine()) != null){
        //process the line
        System.out.println(line);

   1st step:  Extract timestamp 

   2nd step: Compare original and future timestamp (timestamp10daysinfuture )


   }     }

我尝试查看 SO 以首先提取时间戳,但该时间戳的格式与以下链接中提到的不同。因为通常时间戳在文本文件的开头,但在这里它在中间,我认为它需要正则表达式。

How to Read Time and Date from Text File in Java 5?

任何帮助将不胜感激。

【问题讨论】:

  • 我认为你是对的:一个不错的选择是使用正则表达式。如果时间戳具有“奇怪”的格式,您应该获取一些样本并为它们创建一个正则表达式:) 然后,这篇文章可能对您将字符串转换为时间戳对象有用:stackoverflow.com/questions/18915075/…
  • @dimasdmm 是的,我被卡住了。我无法从上述文本文件中提取时间戳。
  • 包含时间戳的行是否总是包含并以### Scenario: - timestamp: 开头?它总是在第 3 行还是可以在其他任何地方?文件中是否有两个以上的时间戳?
  • @Eritrean 是的,它总是包含这个

标签: java regex timestamp text-files


【解决方案1】:

您可以使用正则表达式 (?<=timestamp:\h)\d+(?=\h-) 来检索匹配项。

使用 Java-11:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(getTimeStamp("myfile.txt"));
    }

    static String getTimeStamp(String filePath) throws IOException {
        return Pattern.compile("(?<=timestamp:\\h)\\d+(?=\\h-)")
                    .matcher(Files.readString(Path.of(filePath), StandardCharsets.US_ASCII))
                    .results()
                    .map(MatchResult::group)
                    .findAny()
                    .orElse("");
    }
}

输出:

1620832134319

使用 Java-9:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(getTimeStamp("myfile.txt"));
    }

    static String getTimeStamp(String filePath) throws IOException {
        String str = Files.lines(Paths.get(filePath), StandardCharsets.US_ASCII).collect(Collectors.joining());
        return Pattern.compile("(?<=timestamp:\\h)\\d+(?=\\h-)")
                    .matcher(str)
                    .results()
                    .map(MatchResult::group)
                    .findAny()
                    .orElse("");
    }
}

使用 Java-8:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println(getTimeStamp("myfile.txt"));
    }

    static String getTimeStamp(String filePath) throws IOException {
        String str = Files.lines(Paths.get(filePath), StandardCharsets.US_ASCII).collect(Collectors.joining());
        Matcher matcher = Pattern.compile("(?<=timestamp:\\h)\\d+(?=\\h-)").matcher(str);
        if (matcher.find()) {
            return matcher.group();
        } else {
            return "";
        }
    }
}

regex101 正则表达式的解释:

Positive Lookbehind (?<=timestamp:\h)
    Assert that the Regex below matches
    timestamp: matches the characters timestamp: literally (case sensitive)
    \h matches any horizontal whitespace character (equivalent to [[:blank:]])
\d matches a digit (equivalent to [0-9])
+ matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
Positive Lookahead (?=\h-)
    Assert that the Regex below matches
    \h matches any horizontal whitespace character (equivalent to [[:blank:]])
    - matches the character - literally (case sensitive)

如何处理检索到的时间戳的演示:

import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws IOException {
        String timestamp = "1620832134319";

        // Change the ZoneId as per your requirement e.g. ZoneId.of("Europe/London")
        ZonedDateTime zdt = Instant.ofEpochMilli(Long.parseLong(timestamp)).atZone(ZoneId.systemDefault());
        System.out.println(zdt);

        zdt = zdt.plusDays(10);
        System.out.println(zdt);

        // Custom format
        System.out.println(DateTimeFormatter.ofPattern("MM/dd/uuuu", Locale.ENGLISH).format(zdt));
    }
}

输出:

2021-05-12T16:08:54.319+01:00[Europe/London]
2021-05-22T16:08:54.319+01:00[Europe/London]
05/22/2021

【讨论】:

  • 感谢您帮助我。我收到以下错误:“类型 Matcher 的方法 results() 未定义”和“类型 Path 的 (String) 方法未定义”
  • 它可以从 Java-9 获得。你用的是低版本的JDK吗?
  • 是的,我正在使用 1.8.0_202 cox,这是必须使用的。
  • @rob - 好的......现在,我已经发布了 Java-8 解决方案的更新。我希望它能解决你的问题。
  • @rob:请避免添加来自 cmets 的新要求。问题是关于从给定输入中提取时间戳。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 2016-08-10
  • 1970-01-01
  • 2018-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多