正则表达式从文件中提取哈希 [英] Regular expression to extract hashes from file

查看:113
本文介绍了正则表达式从文件中提取哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这种格式的文件:

I have a file in this format:

5:Name: {"hash":"c602720140e907d715a9b90da493036f","start":"2016-02-20","end":"2016-03-04"}
5:Name: {"hash":"e319b125d71c62ffd3714b9b679d0624","sa_forum":"on","start":"2015-11-14","end":"2016-02-20"}

我正在尝试使用正则表达式提取哈希键和日期.我该怎么办?

I am trying to extract the hash key and date using a regular expression. How can I do it?

我尝试使用此/^ [a-z0-9] {32} $/进行哈希处理,但无法正常工作.

I tried this /^[a-z0-9]{32}$/ for the hash but it doesn't work.

我将不胜感激.

这是一个文本文件,我正在尝试对其进行 preg_match().这是我的代码:

This is a text file, and I'm trying to preg_match() it. Here's my code:

$file = file_get_contents("log.txt");

preg_match("/^[a-z0-9]{32}$/",$file, $hashes);
var_dump($hashes);

我得到一个空数组.

推荐答案

问题是您将匹配项与 ^ $ 绑定在一起,但实际上您想要匹配字符串中间的 .试试这个:

The problem is that you're bounding your match with ^ and $, but you actually want to match something in the middle of the string. Try this:

/(?<=")[a-f0-9]{32}(?=")/

这仅在引号之间匹配.另外,您不需要 a-z ,因为它只能是 a-f .

This will only match between the quotes. Also, you don't need a-z as it can only be a-f.

此外,由于您需要文件中所有数组的所有哈希值,而不仅仅是一个数组,因此需要

Also, since you want an array of all of the hashes in the file and not just one, you need preg_match_all():

php > $file = file_get_contents("hashfile.txt");
php > preg_match_all('/(?<=")[a-f0-9]{32}(?=")/', $file, $matches);
php > var_dump($matches);
array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(32) "c602720140e907d715a9b90da493036f"
    [1]=>
    string(32) "e319b125d71c62ffd3714b9b679d0624"
  }
}
php >

在上面的示例中,匹配项存储在数组 $ matches [0] 中.

The matches are stored in the array $matches[0] in my above example.

这篇关于正则表达式从文件中提取哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆