正则表达式返回不同长度的句子

时间:2015-10-13 23:21:59

标签: php regex

我在开头用不同长度的句子和数字匹配。 我怎么能这样做并返回不同长度的匹配?

例如" 2341'麦克白&#34 ;,     " 2354'饥饿游戏",     " 1236'深红峰"

   preg_match_all("d+\\'\s\w+\s\w+(?(?=w))~", $string, $array);

显然,我对正则表达式和一般编程都很陌生,任何回复都会受到高度赞赏。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用\d+

<强> working demo

如果你想捕获然后使用捕获组

(\d+)

enter image description here

匹配信息

MATCH 1
1.  [0-4]   `2341`
MATCH 2
1.  [17-21] `2354`
MATCH 3
1.  [43-47] `1236`

顺便说一下,如果你有一个多行句子,只需在开头添加^,只匹配以数字开头的行:

^(\d+)

<强> Working demo

enter image description here

答案 1 :(得分:1)

我想这会起作用

/^\d+.*?$/

<强>样本

https://regex101.com/r/fY9yA5/1

REGEX EXPLANATION

^\d+.*?$

Assert position at the beginning of a line «^»
Match a single character that is a “digit” «\d+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match any single character «.*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line «$»