【问题标题】:parsing paragraphs and inserting them as DB record解析段落并将它们作为数据库记录插入
【发布时间】:2013-08-07 04:34:47
【问题描述】:

我正在尝试将记录插入 mysql 数据库。我有一个包含多个段落的文本文件,一个段落必须是一个数据库记录。

我的数据库有 5 列 - 职业、经验、部门、被保险人、备注

我的文本文件具有以下格式 - 我有一个 perl 代码监视存储这些文本文件的目录。问题是可能有两个职业值或只有一个。到目前为止,当 format 只有一个占用值时,我开始从第 n 个索引读取文件数组,在循环中提取偏移量为 5 的所有内容,使段落成为记录。

格式不会改变,它将是以下两段的组合。如何将这些段落分别放入数组中以进行数据库插入?谢谢! ~拉尔夫

### Start of File
Header

Occupation: Analyst3.
Experience: 7
Department: ZAD6A.
Insured: 0
Remarks: None


Occupation: Analyst2.
Occupation: Engineer-I.
Experience: 4
Department: 50021.
Insured: 0
Remarks: New Hire.

Footer
### End Of File

【问题讨论】:

  • 那么如果文件里有两个职业,你想怎么做呢?
  • 我将连接数据库中 Occupation 字段中的 Occupation 值..感谢 Alec 的投球!
  • 所以我可以有类似 ..TextFile1_Arr[0]={Analyst3.,7,ZAD6A.,0,None}...TextFile1_Arr[1]={Analyst2.:Engineer-I. ,4,50021.,0,New Hire.}.. 以此类推 textfile2 .....textfile3.. 以此类推。

标签: regex parsing paragraph


【解决方案1】:
# split the input string into blocks by one or more empty lines
my @blocks = split /\n{2,}/, $input;

# skip Header and Footer by shifting index of @blocks
# get all the value after ':' in the same block
# merge the 1th and 2nd value of the array for duplicated occupation if size == 6
my @results = map { @{$_} == 6 ? ["$_->[0]:$_->[1]", @{$_}[2..5]] : $_ } 
    map { [/:\s*([^\n]+)/g] } @blocks[1..$#blocks-1];

【讨论】:

  • 谢谢亚历克..要试试这个..但是这可以使用正则表达式来完成吗?我事先知道块的数量(块的数量在文件名中)。所以我可以遍历没有块。现在什么最好的正则表达式可以捕获一个块?从 Occupation 开始捕获直到遇到下一个 Occupation 之前?页眉和页脚在所有文件中都是不变的。
  • 试试这个$input =~ /(Occupation.+?)(?=\n{2,})/sg;
  • Alec..this 仅捕获最后一个职业,跳过所有其他职业。
猜你喜欢
  • 2022-09-23
  • 2021-06-26
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多