通过搜索数字/字符通过正则表达式拆分字符串

时间:2014-11-16 22:23:45

标签: php regex

如何分割此字符串......

Any-word 3, with comma 48, 50 -- 51, 527

...进入Any-word 3, with comma48, 50 -- 51, 527?第二部分总是一个数字; optinal有多个数字(如本例所示),可以用','和/或' - '分隔。第二部分也没有任何单词或字母(与第一部分中的数字3不同)。

我需要拆分字符串以检查第二部分是否匹配。如果是这种情况,我只想使用第一场比赛。

还有一些字符串示例:

Any-word 3, with comma 48, 50 -- 51, 527
Anything 12
--Some thing 30-- 51, 1
123,
89
Just words

应该分开:

Any-word 3, with comma|48, 50 -- 51, 527
Anything|12
--Some thing|30-- 51, 1
|123,
|89
Just words|

尝试使用......

preg_match($re, $str, $match);

1 个答案:

答案 0 :(得分:1)

你可以尝试这种模式

^(.*?) (?!.*[a-z])(.*)

Demo

^               # Start of string/line
(               # Capturing Group (1)
  .             # Any character except line break
  *?            # (zero or more)(lazy)
)               # End of # Capturing Group (1)
                # " "
(?!             # Negative Look-Ahead
  .             # Any character except line break
  *             # (zero or more)(greedy)
  [a-z]         # Character Class [a-z]
)               # End of # Negative Look-Ahead
(               # Capturing Group (2)
  .             # Any character except line break
  *             # (zero or more)(greedy)
)               # End of # Capturing Group (2)