我如何使用正则表达式来解决这个问题?

时间:2010-09-11 20:39:51

标签: php regex

我有两个字符串,我需要从中提取数据,但似乎无法使其正常工作。我希望我知道正则表达但不幸的是我没有。我已经阅读了一些初学者教程,但我似乎无法找到能够满足我需要的表达式。

在由相等字符分隔的第一个字符串中,我需要跳过前6个字符并抓取以下9个字符。在相同的角色之后,我需要抓住前4个字符,这是一天和一年。最后,对于这个字符串,我需要剩余的数字,这是YYYYmmdd中的日期。

636014034657089=130719889904

第二个字符串看起来有点困难,因为字符之间的空格不同,但似乎总是由一个空格分隔。有时,分隔数据块的空间多达15或20个。

以下是两个显示空间差异的不同样本。

!!92519 C 01 M600200BLNBRN D55420090205M1O

!!95815      A               M511195BRNBRN            D62520070906  ":%/]Q2#0*&

我最后两个字符串中需要的数据是:

The zip code following the 2 exclamation marks.
The single letter 'M' following that. It always appears to be in a 13 character block
The 3 numbers after the single letter
The next 3 numbers which are the person's height
The following next 3 are the person's weight
The next 3 are eye color
The next block of 3 which are the person's hair color

我需要数据的最后一个块:

我需要得到单个字母,在示例中看起来像是'D'。 跳过接下来的3个号码 最后和剩下的8个数字是YYYYmmdd中的日期

如果有人可以帮我解决这个问题,我将非常感激。

1 个答案:

答案 0 :(得分:2)

对于第一个字符串,您可以使用此正则表达式:

^[0-9]{6}([0-9]{9})=([0-9]{4})([0-9]{4})([0-9]{2})([0-9]{2})$

说明:

^          Start of string/line
[0-9]{6}   Match the first 6 digits
([0-9]{9}) Capture the next 9 digits
=          Match an equals sign
([0-9]{4}) Capture the "day and year" (what format is this in?)
([0-9]{4}) Capture the year
([0-9]{2}) Capture the month
([0-9]{2}) Capture the date
$          End of string/line

第二个:

^!!([0-9]{5}) +.*? +M([0-9]{3})([0-9]{3})([A-Z]{3})([A-Z]{3}) +([A-Z])[0-9]{3}([0-9]{4})([0-9]{2})([0-9]{2})

Rubular

它的工作方式与第一种类似。如果您的数据不完全符合正则表达式所期望的格式,则可能需要稍微调整一下。您可能希望用更精确的内容替换.*?,但我不确定是什么,因为您没有描述您不感兴趣的部分的格式。